vue组件之间通信实录

发布时间:2019-05-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了vue组件之间通信实录脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

1、在vue中父组件是通过props传递数据给子组件

<child-component :prop1="父组件的数据1" :prop2="父组件的数据2"></child-component>

子组件只接受在子组件中定义过的props的值,

Vue.component('child-component', {
  props: ['prop1', 'prop2'], // 定义接收哪些 props
  template: '<div>{{prop1 + prop2}}</div>',
  ...
}

2、父组件调用子组件属性或方法
首先在组件的根元素上通过ref给取个名字,例如:

<child-component ref="aName"></child-component>

然后父组件就可以通过该名称获取到这个组件对象,从而调用里面的属性与方法:

var comp = this.$refs.name;
name.attr;
name.method();

父组件可以通过$children,获取到所有的直接子组件,不包括孙组件;不保证顺序,不是响应式的

3、子组件传递数据给父组件----自定义事件
父组件通过v-on在子组件使用的地方监听子组件触发的事件:

<div id="counter-event-example">
  <p>{{ total }}</p>
//increment是子组件中的事件,意思就是在子组件中increment执行的时候,执行父组件中的incrementTotal方法
  <button-counter v-on:increment="incrementTotal"></button-counter>
  <button-counter v-on:increment="incrementTotal"></button-counter>
</div>
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function (arg) {
      this.total += 1
    }
  }
})

然后在子组件中使用$emit()主动抛出事件:

Vue.component('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
      this.$emit('increment')
       //传递参数
       //this.$emit('increment',arg) 
    }
  },
})

当然如果你想在组件根元素上使用原生事件,可以使用.native修饰符
另外子组件调用父组件事件则可以使用$parent或者$root,详见vue文档;

4、兄弟组件之间通信

vue中兄弟组件之间的通信网上大部分说法都是使用vuex,但是对于小白来说,vuex的初始理解门槛还是有的,所以这里主要用事件巴士讲解一下。

一般在vue的开发中都是模块化开发,所以当涉及到兄弟组件之间的通信的时候,我们可以在入口文件中事先声明一个全局的事件巴士(即一个全局的供vue实例),然后通过他来传导数据。
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import App from './App';
import FastClick from 'fastclick';
import router from './router';
import Vue_resource from 'vue-resource';
import axios from 'axios';
import './common/style/index.less';
Vue.config.productionTip = false;
FastClick.attach(document.body);
Vue.prototype.$http = axios;
/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    render: h => h(App),
    data: {
        eventHub: new Vue()
    }
});
router.push('/goods');

然后便可以全局的使用该实例,进行数据的传输,如下:

//在组件a中触发事件add,并且传递参数1
this.$root.eventHub.$emit('add',1);
//在组件b中监听事件的触发,并处理参数
this.$root.eventHub.$on('add',function(data) {
  //...
})

脚本宝典总结

以上是脚本宝典为你收集整理的vue组件之间通信实录全部内容,希望文章能够帮你解决vue组件之间通信实录所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Vue