vue3在組件上使用v-model


v-model用於在元素上創建雙向數據綁定,負責監聽用戶輸入事件來更新數據。

v-model應用於輸入框

<input v-model="searchText" />
// 等價於
<input :value="searchText" @input="searchText = $event.target.value" />

v-model應用於自定義組件

v-mode用在組件上時,類似與用於input輸入框

<customComp v-model="searchText" />
// 等價於
<customComp :model-value="searchText" @update:model-value="searchText = $event" />

為了能讓組件上的v-model生效,

  1. 需要將這個組件中的某個元素的某個屬性綁定到名為modelValue的prop上(從父組件傳來的值)
  2. 在該元素的某個事件觸發時,將新的值通過自定義的update:modelValue事件拋出。

這里以input元素為例:假設自定義組件中包含一個input元素,代碼如下:

// 子組件
app.component('customComp', {
    props: ['modelValue'],
    emits: ['update:modelValue'],
    template:
        <input :value="modelValue"
            @input="$emit('update:modelValue', $event.target.value)">
})
// 父組件
<customComp v-model="searchText" />

這樣 組件上的v-model指令就能生效。原理還是通過數據綁定和事件觸發,寫法直接可以在組件中使用v-model指令,但組件內要寫出相關傳值與事件觸發代碼。

其他示例:

父組件:

<bindMapComp v-model="childrenDrawer" />

子組件:這里綁定的是 ant-design 中 a-drawer元素的visble屬性

<template>
  <a-drawer
    title=""
    placement="left"
    width="320"
    :closable="false"
    :visible="modelValue"
    @close="onChildrenDrawerClose"
  >
    測試
  </a-drawer>
</template>
<script>
  export default {
    props: {
      modelValue: {
        type: Boolean,
      },
    },
    emits: ['update:modelValue'],
    setup(_, { emit }) {
      const onChildrenDrawerClose = () => {
        // 子組件通過emit事件,向父組件傳值
        emit('update:modelValue', false);
      };
      return {
        onChildrenDrawerClose,
      };
    },
  };
</script>

如不理解可查閱vue官方文檔:https://v3.cn.vuejs.org/guide/component-basics.html#%E5%9C%A8%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BD%BF%E7%94%A8-v-model(vue官方文檔寫的很好,建議反復閱讀,vue的所有知識點官方文檔解釋講解的應該是最好的)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM