• vue组件间通信方式


    平时工作中使用vue比较多,那么组件之间通信的方式有好几种,在此总结一下。

    1,父子组件之间

      1.1,子传父,通过$emit发送事件,然后父组件通过$on来接收事件
      1.2,其实还有一种情况,父传子也可以通过$emit来传递,不过呢这个有一点点特殊,可以参考如下代码,下面就是父组件向子组件传递事件的情况,这个还需要制定组件名称

    <template>
      //这就是引入的一个组件
      <pull ref="testPull">
      <p @click="test">我来试试啦</p>
      </pull>
    </template>
    
    <script>
        methods:{
          test(){
            console.log('emit');
            // this.$emit('pull'); //直接传递不行
            this.$refs.testPull.$emit('pull'); 可以指定组件,然后传递事件
            // this.$Event.$emit('pull') //通过eventBus传递也是可以的
            }
          }
    </script>

    2, 非父子之间的传递

        2.1 一般简单的就用eventBus了,还是贴一下大概的写法吧

       //申明一个独立的空vue实例,一般就写在mian.js中

    
    //main.js:
    
       Vue.prototype.Event=new Vue()

    // 子组件: show1(){ console.log(
    this.Event); this.Event.$emit('host',1) }
    // 父组件:写在mounted中 mounted(){
    this.Event.$on('host', (msg)=>{ console.log('执行了'); console.log(msg); this.show1(); }) }

        2.2 复杂一点的就用vuex了

       2.3 当然,如果不想使用vuex,可以使用简化版的vuex,vue.observe(),代码示例如下:这个和vuex的使用非常像

       

    //在src文件夹根目录想新建store.js  
    import Vue from 'vue'; export const store=Vue.observable({ host_id:'', //自己的uid current_family_data:null, applied_team_id:[], team_id:-1 });
    export const mutations
    ={ set_host_id(host_id){ store.host_id=host_id }, set_current_family(data){ store.current_family_data=data; }, set_applied_team(data){ store.applied_team_id=data; }, set_team_id(data){ store.team_id=data; } };

    //其他组件使用,先引入store.js
     import {store,mutations} from '../store';
      mutations.set_current_family(family);

    基本就这么多吧,之前在网上看别人总结的貌似还有很多其他方法,但是自己主要就是使用上面的几种

  • 相关阅读:
    Get distinct count of rows in the DataSet
    单引号双引号的html转义符
    PETS Public English Test System
    Code 39 basics (39条形码原理)
    Index was outside the bounds of the array ,LocalReport.Render
    Thread was being aborted Errors
    Reportviewer Error: ASP.NET session has expired
    ReportDataSource 值不在预期的范围内
    .NET/FCL 2.0在Serialization方面的增强
    Perl像C一样强大,像awk、sed等脚本描述语言一样方便。
  • 原文地址:https://www.cnblogs.com/ysla/p/11530689.html
Copyright © 2020-2023  润新知