3.11 组件间通信

1.父组件修改子组件的属性
子组件的属性需要父组件提供,例如上一节提到的foot组件,它的公司名,就属于谁使用谁提供。
父元素绑定的如果是变量,那么这个变量的改变就是反应到子组件上。例如这是一个使用了Helloword的组件:
<Helloworld :msg="name"/>
script部分
import HelloWorld from '@/components/HelloWorld.vue';
export default{
    name:'父组件的名字',
    components:{
        HelloWorld
    },
    data():{
        name:''
    }
}
这个name是父组件的一个变量,不再是固定的字符串,这样写的话,子组件的msg就会随着name值变化而变化。从而达到把信息从父组件传到子组件的目的。

2.如果在某些情况,父元素需要直接调用子元素的函数
使用`$refs`获取组件引用
在父组件使用`ref`设置子组件的引用名称,并通过`$refs`获取到子组件引用,然后可以直接通过引用名调用子组件的方法。具体示例:
<CodeModal ref="codeModal"/>
ref相当于给这个组件一个名字,然后在代码中引用
if(this.$refs.codeModal)
    this.$refs.codeModal.exec();

可以通过在子组件中使用`this.$emit(eventName,args)`机制来调用父组件方法,也可以通过`$refs`获取组件引用来调用子组件的方法。

2.使用`this.$emit(eventName,args)机制
在子组件中定义一个需要调用的方法,然后通过`this.$emit(eventName,args)`将事件和参数传递出去,父组件通过`v-on:eventName`来监听事件来调用子组件的方法。具体示例:
<!-- 子组件模板部分 -->
<template>
    <button @click="handleClick">点击</button>
</template>
/*
子组件script部分:
 */
exportdefault{
    methods:{
        handleClick(){
            this.$emit('my-event',
            'hello world');
        }
    }
}
父组件
<!-- 父组件模板部分 -->
<template>
    <div>
        <my-component @my-event="handleMyEvent">
        </my-component>
    </div>
    <br/>
</template>
/*
父组件script部分:
 */
import MyComponent from './MyComponent.vue';
export default{
    components:{
        MyComponent
    },
    methods:{
        handleMyEvent(msg){
            console.log(msg);
        }
    }
}
以上是两种常用的方法。不过需要注意,对于父组件调用子组件方法这种方式,在Vue.js中不是很推荐使用,因为这样会破坏单向数据流的原则。多数情况下我们推荐使用Props和emit来实现父子组件之间的通信。