Vue.js组件通信之自定义事件详解

2020-06-12 20:45:19易采站长站整理


<my-component v-on:click.native="handleClick"></my-component>

使用v-model

Vue 2.x 可以在自定义组件上使用v-model指令。


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<title>使用v-model</title>
</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++;
this.$emit('input',this.counter);
}
}
});

var app = new Vue({
el: '#app',
data: {
total: 0
}
});
</script>
</body>
</html>

仍然是点击按钮+1的效果,不过这次组件$emit()的事件是特殊的input,在使用组件的父级,并没有在<my-component>上使用@input=“handler”,而是使用了v-model板顶的一个数据total。这也可以称作是一个语法糖,因为上面的示例可以间接地用自定义事件来实现:


<div id="myApp">
<p>总数:{{total}}</p>
<my-component1 @input="handlegetTotal"></my-component1>
</div>
<script>
Vue.component('my-component1',{
template: '<button @click="handleClick">+1</button>',
data: function () {
return {
counter: 0
}
},
methods: {
handleClick: function () {
this.counter++;
this.$emit('input',this.counter);
}
}
});

var myApp = new Vue({
el: '#myApp',
data: {
total: 0
},
methods: {
handlegetTotal: function (value) {
this.total = value;
}
}
});
</script>

v-model还可以用来创建自定义的表单输入组件,进行数据双向绑定:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">