記錄--妙用computed攔截v-model,面試管都誇我細

来源:https://www.cnblogs.com/smileZAZ/archive/2023/09/12/17697524.html
-Advertisement-
Play Games

這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 如何避免寫出屎山,優雅的封裝組件,在面試官面前大大加分,從這篇文章開始! 保持單向數據流 大家都知道vue是單項數據流的,子組件不能直接修改父組件傳過來的props,但是在我們封裝組件使用v-model時,不小心就會打破單行數據流的規則, ...


這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助

如何避免寫出屎山,優雅的封裝組件,在面試官面前大大加分,從這篇文章開始!

保持單向數據流

大家都知道vue是單項數據流的,子組件不能直接修改父組件傳過來的props,但是在我們封裝組件使用v-model時,不小心就會打破單行數據流的規則,例如下麵這樣:

<!-- 父組件 -->
<my-component v-model="msg"></my-component>


<!-- 子組件 -->
<template>
  <div>
    <el-input  v-model="msg"></el-input>
  </div>
</template>

<script setup>
defineOptions({
  name: "my-component",
});

const props = defineProps({
  msg: {
    type: String,
    default: "",
  },
});

</script>

v-model實現原理

直接在子組件上修改props的值,就打破了單向數據流,那我們該怎麼做呢,先看下v-model的實現原理:

<!-- 父組件 -->
<template>
  <my-component v-model="msg"></my-component>
  <!-- 等同於 -->
  <my-component :modelValue="msg" @update:modelValue="msg = $event"></my-component>
</template>

emit通知父組件修改prop值

所以,我們可以通過emit,子組件的值變化了,不是直接修改props,而是通知父組件去修改該值!

子組件值修改,觸發父組件的update:modelValue事件,並將新的值傳過去,父組件將msg更新為新的值,代碼如下:

<!-- 父組件 -->
<template>
  <my-component v-model="msg"></my-component>
  <!-- 等同於 -->
  <my-component :modelValue="msg" @update:modelValue="msg = $event"></my-component>
</template>
<script setup>
import { ref } from 'vue'
const msg = ref('hello')
</script>

<!-- 子組件 -->
<template>
  <el-input :modelValue="modelValue" @update:modelValue="handleValueChange"></el-input>
</template>
<script setup>
const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  }
});

const emit = defineEmits(['update:modelValue']);

const handleValueChange = (value) => {
    // 子組件值修改,觸發父組件的update:modelValue事件,並將新的值傳過去,父組件將msg更新為新的值
    emit('update:modelValue', value)
}
</script>

這也是大多數開發者封裝組件修改值的方法,其實還有另一種方案,就是利用計算數據的get、set

computed 攔截prop

大多數同學使用計算屬性,都是用get,或許有部分同學甚至不知道計算屬性還有set,下麵我們看下實現方式吧:

<!-- 父組件 -->
<script setup>
import myComponent from "./components/MyComponent.vue";
import { ref } from "vue";

const msg = ref('hello')
</script>

<template>
  <div>
    <my-component v-model="msg"></my-component>
  </div>
</template>


<!-- 子組件 -->
<template>
  <el-input v-model="msg"></el-input>
</template>
<script setup>
import { computed } from "vue";

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["update:modelValue"]);

const msg = computed({
  // getter
  get() {
    return props.modelValue
  },
  // setter
  set(newValue) {
    emit('update:modelValue',newValue)
  },
});
</script>

v-model綁定對象

那麼當v-model綁定的是對象呢?

可以像下麵這樣,computed攔截多個值

<!-- 父組件 -->
<script setup>
import myComponent from "./components/MyComponent.vue";
import { ref } from "vue";

const form = ref({
  name:'張三',
  age:18,
  sex:'man'
})
</script>

<template>
  <div>
    <my-component v-model="form"></my-component>
  </div>
</template>


<!-- 子組件 -->
<template>
  <div>
    <el-input v-model="name"></el-input>
    <el-input v-model="age"></el-input>
    <el-input v-model="sex"></el-input>
  </div>
</template>
<script setup>
import { computed } from "vue";

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(["update:modelValue"]);

const name = computed({
  // getter
  get() {
    return props.modelValue.name;
  },
  // setter
  set(newValue) {
    emit("update:modelValue", {
      ...props.modelValue,
      name: newValue,
    });
  },
});

const age = computed({
  get() {
    return props.modelValue.age;
  },
  set(newValue) {
    emit("update:modelValue", {
      ...props.modelValue,
      age: newValue,
    });
  },
});

const sex = computed({
  get() {
    return props.modelValue.sex;
  },
  set(newValue) {
    emit("update:modelValue", {
      ...props.modelValue,
      sex: newValue,
    });
  },
});
</script>

這樣是可以實現我們的需求,但是一個個手動攔截v-model對象的屬性值,太過於麻煩,假如有10個輸入,我們就需要攔截10次,所以我們需要將攔截整合起來!

監聽整個對象

<!-- 父組件 -->
<script setup>
import myComponent from "./components/MyComponent.vue";
import { ref } from "vue";

const form = ref({
  name:'張三',
  age:18,
  sex:'man'
})
</script>

<template>
  <div>
    <my-component v-model="form"></my-component>
  </div>
</template>


<!-- 子組件 -->
<template>
  <div>
    <el-input v-model="form.name"></el-input>
    <el-input v-model="form.age"></el-input>
    <el-input v-model="form.sex"></el-input>
  </div>
</template>
<script setup>
import { computed } from "vue";

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(["update:modelValue"]);

const form = computed({
  get() {
    return props.modelValue;
  },
  set(newValue) {
    alert(123)
    emit("update:modelValue", newValue);
  },
});
</script>

這樣看起來很完美,但是,我們在set中alert(123),它卻並未執行!!

原因是:form.xxx = xxx時,並不會觸發computed的set,只有form = xxx時,才會觸發set

Proxy代理對象

那麼,我們需要想一個辦法,在form的屬性修改時,也能emit("update:modelValue", newValue);,為瞭解決這個問題,我們可以通過Proxy代理

<!-- 父組件 -->
<script setup>
import myComponent from "./components/MyComponent.vue";
import { ref, watch } from "vue";

const form = ref({
  name: "張三",
  age: 18,
  sex: "man",
});

watch(form, (newValue) => {
  console.log(newValue);
});
</script>

<template>
  <div>
    <my-component v-model="form"></my-component>
  </div>
</template>


<!-- 子組件 -->
<template>
  <div>
    <el-input v-model="form.name"></el-input>
    <el-input v-model="form.age"></el-input>
    <el-input v-model="form.sex"></el-input>
  </div>
</template>
<script setup>
import { computed } from "vue";

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(["update:modelValue"]);

const form = computed({
  get() {
    return new Proxy(props.modelValue, {
      get(target, key) {
        return Reflect.get(target, key);
      },
      set(target, key, value,receiver) {
        emit("update:modelValue", {
          ...target,
          [key]: value,
        });
        return true;
      },
    });
  },
  set(newValue) {
    emit("update:modelValue", newValue);
  },
});
</script>

這樣,我們就通過了Proxy + computed完美攔截了v-model的對象!

然後,為了後面使用方便,我們直接將其封裝成hook

// useVModel.js
import { computed } from "vue";

export default function useVModle(props, propName, emit) {
    return computed({
        get() {
            return new Proxy(props[propName], {
                get(target, key) {
                    return Reflect.get(target, key)
                },
                set(target, key, newValue) {
                    emit('update:' + propName, {
                        ...target,
                        [key]: newValue
                    })
                    return true
                }
            })
        },
        set(value) {
            emit('update:' + propName, value)
        }
    })
}
<!-- 子組件使用 -->
<template>
  <div>
    <el-input v-model="form.name"></el-input>
    <el-input v-model="form.age"></el-input>
    <el-input v-model="form.sex"></el-input>
  </div>
</template>
<script setup>
import useVModel from "../hooks/useVModel";

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(["update:modelValue"]);

const form = useVModel(props, "modelValue", emit);

</script>

本文轉載於:

https://juejin.cn/post/7277089907974422588

如果對您有所幫助,歡迎您點個關註,我會定時更新技術文檔,大家一起討論學習,一起進步。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1. Redis的數據結構有哪些 1. 字元串(String):字元串是Redis最基本的數據結構。它可以存儲任意類型的數據,包括文本、整數或二進位數據。字元串類型的值最大可以達到512MB。 SET name "John" GET name ``` 將字元串"John"存儲在鍵名為"name"的字 ...
  • Apache DolphinScheduler 是一款開源的分散式任務調度系統,旨在幫助用戶實現複雜任務的自動化調度和管理。DolphinScheduler 支持多種任務類型,可以在單機或集群環境下運行。下麵將介紹如何實現 DolphinScheduler 的自動化打包和單機/集群部署。 自動化打包 ...
  • 1、表名:應體現具體業務含義,全部小寫,多個單詞下劃線分割。 2、欄位:欄位名應體現具體業務含義,全部小寫、多個單詞下劃線分割,選擇合適的數據類型,並且加註釋 每個表應具有以下公共欄位: 欄位名 欄位類型 欄位說明 id int(11)/bigint(20) 自增主鍵id create_user_i ...
  • 在第14屆中國資料庫技術大會(DTCC2023)上,華為雲資料庫運維研發總監李東詳細解讀了GaussDB運維繫統自動駕駛探索和實踐。 ...
  • SQL文件鏈接在最下麵 MySQL子查詢相關使用 子查詢的實質:一個 select 語句的查詢結果能夠作為另一個語句的輸入值。子查詢不僅可用於 where 子句中,還能夠用於 from 子句中,此時子查詢的結果將作為一個臨時表(temporary table)來使用。 一、 單行子查詢 1、 查詢“ ...
  • 引言 Apple MDM (Mobile Device Management) 字面理解就是一種管理移動設備的方式,覆蓋 iOS 5 及更高版本的 iPhone/iPod touch/iPad、Mac OS X 10.7 及更高版本的 Mac、TVOS 9 及更高版本的 Apple TV,標題中的 ...
  • Vue2安裝JSX支持 有時候,我們使用渲染函數(render function)來抽象組件,而渲染函數使用Vue的h函數來編寫Dom元素相對template語法差別較大,體驗不佳,這個時候就派 JSX 上場了。然而在Vue3中預設是帶了JSX支持的,而在 Vue2 中使用 JSX,需要安裝並使用 ...
  • 作為一名全棧工程師,在日常的工作中,可能更側重於後端開發,如:C#,Java,SQL ,Python等,對前端的知識則不太精通。在一些比較完善的公司或者項目中,一般會搭配前端工程師,UI工程師等,來彌補後端開發的一些前端經驗技能上的不足。但並非所有的項目都會有專職前端工程師,在一些小型項目或者初創公... ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...