对于 Vue 封装组建,须要对 v-model 语法糖有理解,如下为总结this
v-model 是针对于父子组件的code
子组件component
绑定 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>
父组件ip
经过 v-model 便可对子组件的值进行绑定操做get
<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 的规则input
子组件it
经过 model 改变关系event
<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>
若此时存在二次封装,须要封装父组件import
父组件
一样绑定 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>