Vue 之$on,$emit的使用
一、说明
$on:监听事件
$emit:触发监听事件
二、代码
1、本页面
<template> <section> <h1>left</h1> <el-button type="primary" @click="isClick">点击</el-button> </section> </template> <script> export default { methods: { isClick() { this.$emit('isLeft', '点击事件!'); } }, mounted() { this.$on('isLeft', (val) => { console.log(val); }); } } </script>
2、非父子组件(通过bus传值)
先创建bus.js文件
import Vue from 'vue'; // 使用 Event Bus const bus = new Vue(); export default bus;
监听:
import bus from '../bus';
export default{
created:{
bus.$on('close_current_tags', function(){//业务})
}
}
触发:
import bus from '../../bus';
export default {
methods:{
back(){
bus.$emit('close_current_tags');
}
}
}