组件自定义事件
给组件绑定自定义事件
Vue2中子组件如何给父组件传递数据?
以下实例通过组件自定义事件提供一种解决方案
以下实例中components中包含两个组件,分别为:
StudenT.vue
<template> <div class="student"> <h2>学生姓名:{{ name }}</h2> <h2>学生年龄:{{ age }}</h2> <button @click="sendStudentName">按钮</button> </div> </template> <script> export default { name: "studenT", data() { return { name: "cxy", age: 18, }; }, methods: { sendStudentName() { //触发student组件实例身上的atguigu事件 this.$emit("atguigu",this.name); }, }, }; </script> <style> .student { background-color: skyblue; } </style>
SchooL.vue
<template> <div class="school"> <h2>学校名称:{{ name }}</h2> <h2>学校地址:{{ address }}</h2> </div> </template> <script> export default { name: "SchooL", data() { return { name: "wust", address: "wuhan", }; }, }; </script> <style> .school { background-color: khaki; } </style>
-
通过父组件给子组件绑定一个自定义事件:子给父传递数据(使用@或v-on):App.vue代码如下
<template> <div class="app"> <h2>子组件传给父组件</h2> <SchooL></SchooL> <!-- 通过父组件给子组件绑定一个自定义事件:子给父传递数据 ,第一种写法,使用@或v-on--> <StudenT v-on:atguigu="getStudentName"></StudenT> <!-- 给student组件的实例对象vc绑定一个atguigu事件 --> <!-- 给谁绑定事件让谁触发事件,这个atguigu是给student组件的实例对象绑定的事件 --> </div> </template> <script> import SchooL from "./components/School.vue"; import StudenT from "./components/Student.vue"; export default { name: "App", components: { SchooL, StudenT, }, methods: { getStudentName(name) { console.log("App收到了学生名",name); }, }, mounted(){ this.$refs.student.$on('atguigu',this.getStudentName) } }; </script> <style> .app { background-color: gray; } </style> 通过父组件给子组件绑定一个自定义事件:子给父传递数据,第二种写法
2.第二种写法:挂载ref属性
<template>
<div class="app">
<h2>子组件传给父组件</h2>
<SchooL></SchooL>
<StudenT ref="student"></StudenT>
</div>
</template>
<script>
import SchooL from "./components/School.vue";
import StudenT from "./components/Student.vue";
export default {
name: "App",
components: {
SchooL,
StudenT,
},
methods: {
getStudentName(name) {
console.log("App收到了学生名",name);
},
},
mounted(){
this.$refs.student.$on('atguigu',this.getStudentName)
}
};
</script>
<style>
.app {
background-color: gray;
}
</style>
解绑自定义事件
销毁当前组件的实例
销毁vm
总结
来源:尚硅谷vue2视频学习