zoukankan      html  css  js  c++  java
  • 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 的开发指引来处理组件之间的通信。

  • 相关阅读:
    个人冲刺二(7)
    个人冲刺二(6)
    个人冲刺二(5)
    个人冲刺二(4)
    对称二叉树 · symmetric binary tree
    108 Convert Sorted Array to Binary Search Tree数组变成高度平衡的二叉树
    530.Minimum Absolute Difference in BST 二叉搜索树中的最小差的绝对值
    pp 集成工程师 mism师兄问一问
    17. Merge Two Binary Trees 融合二叉树
    270. Closest Binary Search Tree Value 二叉搜索树中,距离目标值最近的节点
  • 原文地址:https://www.cnblogs.com/kuku/p/14791596.html
Copyright © 2011-2022 走看看