1.两种绑定方式比较
以父组件fatherValue属性绑定到子组件为例:
绑定方式 | version | 父组件 | 子组件 | 传值到父组件 | 特点 |
---|---|---|---|---|---|
.sync | 2.30+ | :father-value.sync=“fatherValue” | fatherValue: { type: String, default: ‘’ } | this.$emit(‘update:fatherValue’, this.childValue) | 可绑定到子组件任意属性 |
v-model | 2.20+ | v-model=“fatherValue” | value: { type: String, default: ‘’ } | this.$emit(‘input’, this.childValue) | 绑定到子组件value属性 |
2. 流程
- 父组件属性绑定到子组件
- 子组件触发事件
- 在子组件事件中,通过$emit 触发父组件的事件
3. [.sync] 修饰符
.sync 方式可以把父组件属性绑定到子组件任意属性上
eg: 以父组件fatherValue属性绑定到子组件fatherValue属性为例:
father.vue 父组件:
<template>
<div>
<table>
<colgroup>
<col width="30%">
<col width="20%">
<col width="20%">
<col width="30%">
</colgroup>
<tr>
<td></td>
<td>
fatherValue:
<Input v-model="fatherValue" placeholder="fatherValue" />
</td>
<td>
child组件值:
<child :father-value.sync="fatherValue" />
</td>
<td></td>
</tr>
</table>
</div>
</template>
<script>
import child from './Child'// 引入Child子组件
export default {
name: 'Father',
components: {
child
},
data() {
return {
fatherValue: '35174'
}
}
}
</script>
Child.vue 子组件
<template>
<div><Input v-model="childValue" @on-change="onChange" /></div>
</template>
<script>
export default {
name: 'Child',
props: {
fatherValue: { type: String, default: '' }
},
data () {
return {
childValue: this.fatherValue
}
},
methods: {
onChange() {
this.$emit('update:fatherValue', this.childValue)
}
}
}
</script>
4. v-model 方式
v-model 方式只能把父组件属性绑定到子组件value属性上。
<input v-model="fatherValue" />
<!-- v-model方式等于下面的代码 -->
<input :value="fatherValue" @input="fatherValue= $event.target.value" />
eg: 以父组件fatherValue属性绑定到子组件为例:
father.vue 父组件:
<template>
<div>
<table>
<colgroup>
<col width="30%">
<col width="20%">
<col width="20%">
<col width="30%">
</colgroup>
<tr>
<td></td>
<td>
fatherValue:
<Input v-model="fatherValue" placeholder="fatherValue" />
</td>
<td>
child组件值:
<child v-model="fatherValue" />
</td>
<td></td>
</tr>
</table>
</div>
</template>
<script>
import child from './Child'// 引入Child子组件
export default {
name: 'Father',
components: {
child
},
data() {
return {
fatherValue: '35174'
}
}
}
</script>
Child.vue 子组件
<template>
<div><Input v-model="childValue" @on-change="onChange" /></div>
</template>
<script>
export default {
name: 'Child',
props: {
value: { type: String, default: '' }
},
data () {
return {
childValue: this.value
}
},
methods: {
onChange() {
this.$emit('input', this.childValue)
}
}
}
</script>