根据组件关系划分
- 父子
- 跨级
- 无关系
父子
props/$emit,$on
父
<template> <div> <test3-a :value="value" @input="handleChange"></test3-a> </div></template><script>import test3A from '../components/test3-a.vue'export default { components: { test3A }, data () { return { value: 1 } }, methods: { handleChange (val) { this.value = parseInt(val) } }}</script>
子
<template> <div> <button @click="increase(-1)">减1</button> <span> {{currentValue}} </span> <button @click="increase(1)">加1</button> </div></template><script>export default { props: { value: { type: Number } }, data () { return { currentValue: this.value } }, methods: { increase (val) { this.currentValue = this.value + val this.$emit('input', this.currentValue) } }}</script>
props/$emit,$on(v-model写法)
v-model 是一个语法糖,可以拆解为 props: value 和 events: input。就是说组件必须提供一个名为 value 的 prop,以及名为 input 的自定义事件
父
<template> <div> <test3-a v-model="value"></test3-a> </div></template><script>import test3A from '../components/test3-a.vue'export default { components: { test3A }, data () { return { value: 1 } }}</script>
子(不用修改)
<template> <div> <button @click="increase(-1)">减1</button> <span> {{currentValue}} </span> <button @click="increase(1)">加1</button> </div></template><script>export default { props: { value: { type: Number } }, data () { return { currentValue: this.value } }, methods: { increase (val) { this.currentValue = this.value + val this.$emit('input', this.currentValue) } }}</script>
props/$emit,$on(.sync写法)
.sync 不是真正的双向绑定,而是一个语法糖,修改数据还是在父组件完成的,并非在子组件
父
<template> <div> <test3-a :value.sync="value"></test3-a> </div></template><script>import test3A from '../components/test3-a.vue'export default { components: { test3A }, data () { return { value: 1 } }}</script>
子
<template> <div> <button @click="increase(-1)">减1</button> <span> {{value}} </span> <button @click="increase(1)">加1</button> </div></template><script>export default { props: { value: { type: Number } }, methods: { increase (val) { this.$emit('update:value', this.value + val) } }}</script>