vue组件之间通信实录

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

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

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

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

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

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

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

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

{{ total }}

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

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

Vue.component('button-counter', {
  template: '',
  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) {
  //...
})

你可能感兴趣的:(javascript,vue-router,vuex,vue.js)