component_communication_TwoWayCommunicationViaVModel
by edith_tang
HTML
<div id="app">
<p>
总数:{{ total }}
</p>
<!--
v-model可以接收到以特殊名称,也就是`input`命名的自定义事件,进而更新total的值
-->
<my-component v-model="total"></my-component>
<!--
监听点击事件,进而递减total的值
-->
<button @click="handleReduce">- 1</button>
</div>
CSS
button {
border-radius: 50%;
width: 33px;
height: 33px;
border: none;
background-color: skyblue;
color: #fff;
font-weight: bold;
margin-right: 20px;
}
JavaScript
Vue.component('my-component', {
// 接收一个value属性
template: '<input :value="value" @input="updateValue">',
props: ['value'],
methods: {
// 触发一个以`input`命名的自定义事件,并且将子组件输入框内的当前的值传递出去
updateValue: function() {
this.$emit('input', event.target.value);
}
}
})
var app = new Vue({
el: '#app',
data: {
total: 100
},
methods: {
handleReduce: function() {
this.total--;
}
}
})