Vue之子组件向父组件传值之$emit
完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="../js/vue.js"></script>
<title>componet05</title>
</head>
<body>
<div id="app">
<father></father>
</div>
<script>
//child component
let child = Vue.component('child', {
//子组件模板里,事件绑定自定义方法
template: `<div>
<h1>子组件</h1>
<button @click="passMsg">子向父传值</button>
</div>`,
//子组件内自定义方法passMsg
methods: {
passMsg() {
this.$emit('showMsgEvent', '我是子组件过来的!')//第一个参数是要触发的事件名,第二参数是传入值
}
}
})
//ParentComponet
Vue.component('father', {
data() {
return {
fatherMessage: "I am father message"
}
},
//在父模板里调用子组件,并在子组件里绑定父组件里的自定义方法,从而实现子组件向父主件传值
template: `<div>
<h1>父组件</h1>
<h3>{{fatherMessage}}</h3>
<child @showMsgEvent="showMsg"></child>
</div>`,
components: {
child
},
//父组件里自定义方法
methods: {
showMsg(val) {
this.fatherMessage = val
}
}
})
// root
new Vue({
el: '#app',
})
</script>
</body>
</html>
运行效果如图:
点击按钮后
总结:
1.<button @click="passMsg">子向父传值</button>
//子组件模板里,事件绑定自定义方法
2.`
//子组件方法里,用$emit(),定义要触发的事件名及传入参数值。
3.
//在父模板里调用子组件,并在子组件里绑定父组件里的自定义方法,从而实现子组件向父主件传值