父vue
<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>
子this
<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>
v-model 是一個語法糖,能夠拆解爲 props: value 和 events: input。就是說組件必須提供一個名爲 value 的 prop,以及名爲 input 的自定義事件spa
父雙向綁定
<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>
子(不用修改)code
<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>
.sync 不是真正的雙向綁定,而是一個語法糖,修改數據仍是在父組件完成的,並不是在子組件component
父事件
<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>
子ip
<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>