美文网首页
两个组件没有联系的时候,如何在一个组建中触发另一个组件中的东西

两个组件没有联系的时候,如何在一个组建中触发另一个组件中的东西

作者: 执念_6afc | 来源:发表于2019-11-14 20:18 被阅读0次

定义一个全局组件

import Vue from 'vue'
import axios from 'axios'

import App from './App'
import router from './router'

import iView from 'iview'
import 'iview/dist/styles/iview.css'
Vue.use(iView)

window.eventBus = new Vue();//注册全局事件对象(定义的全局组件,放在main.js中)

Vue.http = Vue.prototype.$http = axios

在一个组建中触发

<template>
  <div >
        <div><h2>文件列表</h2></div>
        <div v-for="item in file_list">
              <span >{{ item }}&nbsp;&nbsp;&nbsp;<button @click="down(item)">下载</button></span>
        </div>
  </div>
</template>
<script>
  export default {
      data(){
          return {
              file_list:['1.txt','2.txt']
          }
      },
      created(){
      },
      methods: {
        down(name){
            eventBus.$emit('eventBusName', name);
        }
      }
  }
</script>

在另一个组建中监听

<template>
  <div >
        <div><h2>文件下载列表</h2></div>
  </div>

</template>
<script>
  export default {
      data(){
        return {
        }
      },
      created(){
        eventBus.$on('eventBusName',function(data){
            console.log(data);
        });
      },
      methods: {
      }
  }
</script>

重点: 在main.js中引入了window.eventBus = new Vue();
在某一个组建中methods中的任何一个方法中都可以触发该事件(将触发事件放在函数中)eventBus.emit('自定义名字',要传的变量); 需要被触发的那个组建中在created中接收 eventBus.on('自己定义的名字',要传过来的变量),function(data){
cosnole.log(data);//输出为要传过来的变量
})

相关文章

网友评论

      本文标题:两个组件没有联系的时候,如何在一个组建中触发另一个组件中的东西

      本文链接:https://www.haomeiwen.com/subject/imrdictx.html