对于$emit的用法
可以总结:
- 子组件通过$emit的方式,调用父组件中的事件,进行传递数据
- $emit函数只能在子组件中使用
一、子组件
<div>
<!-- 1 给子组件绑定一个点击事件 -->
<el-button type="primary" size="small" @click="btnFn">我是子组件</el-button>
</div>
</template>
<script>
export default {
methods: {
// 2 声明事件处理函数
btnFn() {
console.log("点击到了");
// 3 子传父
// 执行$emit函数,会调用父组件中名为sonEvent的函数再将"hello world"的值传过去
this.$emit("sonEvent", "hello world");
},
},
};
</script>
从上面子组件的代码上看,我们可以知道,当子组件被点击的时候,会触发btnFn事件,再声明btnFn()事件处理函数,之后执行$emit函数,该emit函数会调用下面父组件中名为sonEvent的事件,并将“hello world”的值传递给父组件。
二、父组件
<div id="app">
<!-- 4 接收子传父 @inputFn="fatInput" -->
<!-- @sonEvent 与子组件this.$emit('sonEvent',...)起的名字一致 -->
<son @sonEvent="sonFn"></son>
</div>
</template>
<script>
import son from "./components/son.vue";
export default {
name: "app",
components: {
son,
},
methods: {
// 5 接收参数
sonFn(data) {
console.log(data);
},
},
};
</script>
父组件的sonEvent事件被触发,调用sonFn函数,可以在控制台上打印接收到子组件传递过来的值