Vue 父子组件通信方式

Vue 父子组件通信方式

以前在写 WinForm 程序, 或 WebForm 程序的时候,父子组件进行通信的时候一般是调用对方的属性或方法即可,

Vue 里面的组件有个 props 属性,用来设置父组件向子组件传递数据属性,子属性需要向父组件发起通知时,一般使用 this.$emit 方法引发一个事件,父组件需要监听此事来做处理。

<template>
    <div class="parent">
        <child :msg="msg" @change="change" />
    </div>
</template>
<script>
export default {
    data: function() {
        return {
            msg: "Hello"
        }
    },
    methods: {
        change: function(name) {
            this.msg = "Hello " + name;
        }
    }
}
</script>
<template>
    <div class="child">
        <span>{{msg}}</span>
        <br />
        <button @click="change">change</button>
    </div>
</template>
<script>
export default {
    props: {
        msg: String
    },
    methods: {
        change: function() {
            this.$emit('change', 'zhangshang');
        }
    }
}
</script>

在子组件里不能直接修改 props 属性的值,会出错,但是有时候我们只需要简单的修改一父组件的值,监听事件,发起事件感觉稍显麻烦,需要一个更直接方式来处理,

子组件调用父组件

在 Vue 的组件上有一个 $parent 的属性,指向组件的父组件,通过此属性可以直接调用父组件的方法:

this.$parent.methodName(arg);

// 直接设置属性
this.$parent.msg = "Hello World!!!"; // 直接设置父组件的

// 调用 $set 方法
this.$set(this.$parent, 'msg', 'Hello, World!!!');
this.$parent.$set(this.$parent, 'msg', 'Hello, World');
Vue.set(this.$parent, 'msg', 'Hello, World');

父组件调用子组件

和子组件调用父组件的方式一下,在父组件中只需要获取到了子组件的引用,通过此引用即可调用相关的方法或属性。

总结

通过引用来从外部修改组件内部的数据,这种方式只用于简单的场景,最好还是按 Vue 的开发指引来处理组件之间的通信。

原文地址:https://www.cnblogs.com/kuku/p/14791596.html