vue组件之间通讯实录

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

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

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

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

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

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

而后父组件就能够经过该名称获取到这个组件对象,从而调用里面的属性与方法:web

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

父组件能够经过$children,获取到全部的直接子组件,不包括孙组件;不保证顺序,不是响应式的vuex

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

<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()主动抛出事件:app

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文档;less

四、兄弟组件之间通讯模块化

vue中兄弟组件之间的通讯网上大部分说法都是使用vuex,可是对于小白来讲,vuex的初始理解门槛仍是有的,因此这里主要用事件巴士讲解一下。vue-resource

通常在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) {
  //...
})
相关文章
相关标签/搜索