<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>7.3.2自定义组件上使用v-model</title>
<style>
[v-cloak]{
display: none;
}
</style>
</head>
<body>
<div id="app" v-cloak>
<p>总数: {{total}}</p>
<!-- <my-component v-model="total"></my-component>无需监听, "v-model" 绑定数据,效果同下 -->
<my-component @input="getTotal"></my-component><!-- 监听自定义事件 "input" -->
<br><br><br>
<my-component2 v-model="total"></my-component2><!-- 接收到子组件传递过来的值,通过特殊的 "v-model" ,直接将传递过来的值赋值到 "total" ,达到数据同步 -->
<button @click="handlerReduce">-1</button><!-- 绑定点击一次总数 -1 的事件 -->
</div>
<script type="text/javascript" src="/node_modules/vue/dist/vue.js"></script>
<script type="text/javascript">
Vue.component("my-component",{
template: `<button @click="handleClick">+1</button>`,
data () {
return {
counter: 0
}
},
methods: {
handleClick: function () {
this.counter++;
this.$emit("input",this.counter);//这里使用特殊的 "input" 事件名称
}
}
})
Vue.component("my-component2",{
props: ['value'],//还没搞明白为什么这个 "value" 是代替 "v-model" 的
//接收一个value属性
template: `<input :value="value" @input="updateValue" type='number'>`,
methods: {
updateValue: function (event) {
this.$emit("input",event.target.value)//每次在输入框更新数据的时候,将数据通过 "$emit()" 传递给父组件
}//在有新的 "value" 值的时候触发input事件并更新
}
})
var vm = new Vue({
el: "#app",
data: {
total: 123
},
methods: {
getTotal: function (value) {
this.total = value;
},
handlerReduce: function () {
this.total--;
}
}
})
</script>
</body>
</html>
网友评论