vue2.0自定义事件
我们知道父组件是使用props传递数据给子组件,如果子组件要把数据传递回去,怎么办? 那就是要自定义事件!使用v-on绑定自定义事件 每个Vue实例都实现了事件接口(Events interface), 即 使用$on(eventName) 监听事件 $emit(eventName) 触发事件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="../vue2.2.js"></script>
<!--<script src="../vue2.1.6.js"></script>-->
<link rel="stylesheet" href="styles/demo.css" />
</head>
<body><div id="app">
<table>
<tr>
<th colspan="3">父组件数据</th>
</tr>
<tr>
<td>名字</td>
<td>{{name}}</td>
<td><input type="text" v-model="name" /></td>
</tr>
<tr>
<td>年龄</td>
<td>{{age}}</td>
<td><input type="text" v-model="age" /></td>
</tr>
</table>
<my-component :my-name="name" :my-age="age" @change-name="setName" @change-age="setAge"></my-component>
</div>
<template id="myComponent">
<table>
<tr>
<th colspan="3">子组件数据</th>
</tr>
<tr>
<td>名字</td>
<td>{{myName}}</td>
<td><input type="text" v-model="myName" /></td>
</tr>
<tr>
<td>年龄</td>
<td>{{myAge}}</td>
<td><input type="text" v-model="myAge" /></td>
</tr>
</table>
</template>
<script>
var vm = new Vue({
el: "#app",
data: {
name: "小明",
age: 24
},
components: {
'my-component': {
template: "#myComponent",
props: ["myName", "myAge"],
watch: { //监听外部对props属性myName,myAge的变更
myName: function(val) {
this.$emit("change-name", val) //组件内对myName变更后向外部发送事件通知
},
myAge: function(val) {
this.$emit("change-age", val) //组件内对myAge变更后向外部发送事件通知
}
}
}
},
methods: {
setName: function(val) {
this.name = val; //外层调用组件方法注册变更方法,将组件内的数据变更,同步到组件外的数据状态中
},
setAge: function(val) {
this.age = val;
}
}
})
</script>
</body>
</html>
欢迎关注小程序,感谢您的支持!