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