v-model是一个语法糖,我这边用来做父子组件属性的双向绑定
下面是vue2.2
出的一个解决方案
父
这里的 isClassReport
的值将会传入这个名为 checked
的 prop。同时当 <el-checkbox>
触发一个 change
事件并附带一个新的值的时候,这个 isClassReport
的 property 将会被更新。
<commission
class="mt-15"
title="报班提成佣金"
v-model="isClassReport"
/>
子
一个组件上的 v-model
默认会利用名为 value
的 prop 和名为 input
的事件,但是像单选框、复选框等类型的输入控件可能会将 value
attribute 用于不同的目的
。model
选项可以用来避免这样的冲突:
因为不能直接修改父级传来的prop值,这里用到了原生语法来进行子传父修改值
<el-checkbox
:label="title"
:value="checked"
@change="($event) => $emit('change', $event)"
></el-checkbox>
model: {
prop: "checked",
event: "change",
},
props: {
checked: {
type: Boolean,
default: false,
}
}
.sync 修饰符
这里是vue2.3
出的一个解决方案
// 父
<text-document :title.sync="title"></text-document>
// 子
this.$emit('update:title', newTitle)
旧版用法
// 父
<currency-input v-model="price"></currentcy-input>
// 子
@input="$emit('input', $event.target.value)"
props: ['value'] // 默认
v-model在input元素上时的使用
$event是事件对象
<input v-model="sth" /> // 语法糖
<input :value="sth" @input="sth = $event.target.value" /> // 原生语法