自定义 v-model 的使用方法

633 阅读1分钟

基础知识

官方文档

一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件

但是像单选框、复选框等类型的输入控件可能会将 value attribute 用于不同的目的model 选项可以用来避免这样的冲突

将v-model绑定到组件上

默认绑定 valueinput

  1. 在父组件 father.vue上为子组件son.vue绑定v-model
<template>
    <div>
        <Son v-model="flag">
        </Son>
    </div>
</template>

<script>
// 导入子组件
import Son from './son.vue'
export default {
  components: {
    FollowUser
  },
  data(){
    return {
      flag:true
    }
  }
}
</script>
  1. 在子组件 son.vue上,
    • 通过props的value,接收父组件上v-model传入的值
    props: {
        value: {
          type: Boolean,
          required: true
        }
    }
    
    • 通过 $emit 触发父组件的input事件
    this.$emit('input', !this.value)
    
<template>
  <van-icon
    @click="onClick"
    :color="value ? '#ffa500' : ''"
    :name="value ? 'star' : 'star-o'"
  />
</template>

<script>
export default {
  props: {
    value: {
      type: Boolean,// 接收父组件 v-model传过来的值,即flag
      required: true
    },
  },
  methods: {
    // 点击 按钮
    onClick() {
        // 通过触发父组件的默认input事件,去更新父组件的flag值
        // 即 使父组件的 flag改为false
        this.$emit('input', !this.value)  
    }
  }
}
</script>

自定义事件的名称

  • 在子组件 son.vue上,
    • 通过props的value,接收父组件上v-model传入的值
    model: {
        prop: 'isCheck', // 用来接收 v-model的值
        event: 'changeStatus' // 通过触发changeStatus事件,来向 v-model传值
    },
    props: {
        // 接收的v-model传入的值
        isCheck: {
          type: Boolean,
          required: true
        }
    }
    
    • 通过 $emit 触发父组件的input事件
    this.$emit('changeStatus', !this.isCheck)
    
<template>
  <van-icon
    @click="onClick"
    :color="isCheck ? '#ffa500' : ''"
    :name="isCheck ? 'star' : 'star-o'"
  />
</template>

<script>
export default {
  model: {
      prop: 'isCheck', // 用来接收 v-model的值
      event: 'changeStatus' // 通过触发changeStatus事件,来向 v-model传值
  },
  props: {
      // 接收的v-model传入的值
      isCheck: {
        type: Boolean,
        required: true
      }
  },
  methods: {
    // 点击 按钮
    onClick() {
        // 通过触发父组件的默认input事件,去更新父组件的flag值
        // 即 使父组件的 flag改为false
        this.$emit('changeStatus', !this.isCheck)  
    }
  }
}
</script>

截屏2021-09-01 下午3.30.02.png