一、前言

对于 Vue 封装组建,需要对 v-model 语法糖有理解,以下为总结

二、基础

v-model 是针对于父子组件

子组件

绑定 value 属性和 input 事件,value 属性的值通过 porp 传入,出发的 input 事件通过 $emit('input', xxx) 传出

<template>  <input :value="value" @input="$emit('input', $event.target.value)" /></template><script>export default {  name: 'ChildComponent',  props: {    value: String  }}</script>

父组件

通过 v-model 即可对子组件的值进行绑定操作

<template>  <child-component v-model="value"></child-component></template><script>import ChildComponent from "..."export default {  name: 'FatherComponent',  components: { ChildComponent },  data () {    return {      value: ''    }  }}</script>

三、自定义规则

可改变子组件必须接收 prop: value,$emit:input 的规则

子组件

通过 model 改变关系

<template>  <input :value="select" @input="$emit('change', $event.target.value)" /></template><script>export default {  name: 'ChildComponent',  model: {    prop: 'select',    event: 'change'  }  props: {    select: String  }}</script>

四、嵌套 v-model

若此时存在二次封装,需要封装父组件

父组件

同样绑定 value 属性和 input 事件

<template>  <child-component :value="value" @input="handleChange"></child-component></template><script>import ChildComponent from "..."export default {  name: 'FatherComponent',  components: { ChildComponent },  props: {    value: String  },  methods: {    handleChange (val) {      this.$emit('input', val)    }  }}</script>

爷爷组件

通过 v-model 绑定父组件的值

<template>  <father-component v-model="value"></father-component></template><script>import FatherComponent from "..."export default {  name: 'GrandFather',  components: { FatherComponent },  data () {    return {      value: ''    }  }}</script>