双向绑定有两种方式:
1. v-model 绑定方式,
子组件实现方式
<template> <div> <button @click = "plusClick">+</button> <button @click = "minuClick">-</button> </div> </template> <script > import Vue from 'Vue'; export default { name: 'count', model: { prop: 'count', //v-model绑定的数据,相当于别名,可以和父组件中的变量名称不一样。 event: 'mySign' // 自定义组件发送的信号名称。 }, props: { count: '',// 必须和model 对象中的变量对应。 age: '' }, data () { return { incount: this.age } }, methods:{ plusClick(){ this.incount++; this.$emit('mySign', this.incount); }, minuClick(){ this.incount--; this.$emit('mySign', this.incount); } }, 父组件调用:
<div>age out: {{age}}</div> <count v-model="age" :age="age"></count>
这样就可以满足子组件改变父组件的值。2。sync
父组件:
子组件:<child2 :name.sync="name"></child2>
<template> <div> child2 in : <input type="text" v-model="localName"/> </div> </template> <script > import Vue from 'Vue'; export default { name: 'child2', props:['name'], data () { return { localName: this.name } }, watch:{ localName: function(newVal,old) { this.$emit('update:name', newVal); console.log("new:"+newVal+";old="+old); } },