使用 v-model
可以在自定义组件上使用 v-model 指令。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用v-model</title>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
</head>
<body>
<div id="app">
<p>总数:{{total}}</p>
<my-component v-model="total"></my-component>
</div>
<script>
Vue.component("my-component", {
template: '<button @click="handleClick">+1</button>',
data: function () {
return {
counter: 0
}
},
methods: {
handleClick: function () {
this.counter += 1;
this.$emit("input", this.counter);
}
},
});
var app = new Vue({
el: "#app",
data: {
total: 0
}
});
</script>
</body>
</html>
上面的例子可以使用自定义事件来实现。v-model 指令可以看作是一个语法糖。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用v-model</title>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
</head>
<body>
<div id="app">
<p>总数:{{total}}</p>
<my-component @input="handleGetTotal"></my-component>
</div>
<script>
Vue.component("my-component", {
template: '<button @click="handleClick">+1</button>',
data: function () {
return {
counter: 0
}
},
methods: {
handleClick: function () {
this.counter += 1;
this.$emit("input", this.counter);
}
},
});
var app = new Vue({
el: "#app",
data: {
total: 0
},
methods: {
handleGetTotal: function (total) {
this.total = total;
}
},
});
</script>
</body>
</html>
此外,v-model 还可以用来创建自定义的表单输入组件,进行数据的双向绑定。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用v-model</title>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
</head>
<body>
<div id="app">
<p>总数:{{total}}</p>
<my-component v-model="total"></my-component>
<button @click="handleReduce">-1</button>
</div>
<script>
Vue.component("my-component", {
props: ["value"],
template: '<input :value="value" @input="updateValue">',
methods: {
updateValue: function (event) {
this.$emit("input", event.target.value);
}
},
});
var app = new Vue({
el: "#app",
data: {
total: 0
},
methods: {
handleReduce: function () {
this.total -= 1;
}
},
});
</script>
</body>
</html>
要实现这样一个组件需要满足两个要求:
- 接收一个 value 属性。
- 在有新的 value 时触发 input 事件。
网友评论