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实例作为中央事件总线

**main.js**
let bus = new Vue()
Vue.prototype.bus = bus
**header组件**
<template>
    <header @click="changeTitle">{{title}}</header>
</template>
<script>
export default {
    name: 'header',
    data () {
        return {
            title: '头部'
        }
    },
    methods: {
        changeTitle () {
            this.bus.$emit('toChangeTitle','首页')
        }
    }
}
</script>
**footer组件**
<template>
    <footer>{{txt}}</footer>
</template>
<script>
export default {
    name: 'footer',
    mounted () {
        this.bus.$on('toChangeTitle', function (title) {
            console.log(title)
        })
    },
    data () {
        return {
            txt: '尾部'
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40954793/article/details/82252880