zoukankan      html  css  js  c++  java
  • Vue.js父子组件和非父子组件间的传值通信

    父子组件的传值通信

    父组件向子组件传值

    • 父组件:
    <template>
        <child :message="parentMessage"></child>
    </template>
    
    data () {
        return {
            parentMessage: "this is a message from parent"
        }
    }
    
    • 子组件:
    <template>
        <p>{{message}}</p>
    </template>
    
    /* 一般形式 */
    data () {
        props: ["message"]
    }
    
    /* 指定接收类型 */
    data () {
        props: {
            message: {
                type: String, //接收类型
                default: "this is the default value" // 默认值
            }
        }
    }
    

    子组件向父组件传值

    Note 子组件不能直接更改父组件中的内容,因此可以通过子组件触发事件来传值给父组件。

    • 父组件:
    <template>
        <div class="root">
            /* 自动监听子组件注册的 getChildValue 事件*/
            <child @getChildValue="receive"></child>
            
            <p>{{valueFromChild}}</p>
        </div>
    </template>
    
    data () {
        return {
            valueFromChild: "defaultValue"
        }
    },
    methods: {
        receive (valueFromChild) {
            this.valueFromChild = valueFromChild
        }
    }
    
    • 子组件:
    <template>
        <button @click="sendValueToParent">click to send value to parent</button>
    </template>
    
    data () {
        return {
            childValue: 'this is child Value'
        }
    },
    methods: {
        sendValueToParent () {
            /* 将 childValue 传递给父组件 */
            this.$emit('getChildValue', this.childValue)
        }
    }
    

    非父子组件之间的传值通信

    1. 创建 eventBus.js
    import Vue from 'vue'
    
    var bus = new Vue()
    
    export default bus
    
    1. 组件 A
    <template>
        <div class="root">
            <button @click="sendMessageToB">click here to send a message to B</button>
        </div>
    </template>
    
    import eventBus from '.../eventBus.js'
    
    data () {
        return {
            message: "message from A"
        }
    },
    methods: {
        sendMessageToB () {
            eventBus.$emit('transfer', this.message); 
        }
    }
    
    
    1. 组件 B
    <template>
        <div class="root">{{messageFromA}}</div>
    </template>
    
    import eventBus from '.../eventBus.js'
    
    data () {
        return {
            messageFromA: "defaultValue"
        }
    },
    created () {
        eventBus.$on('transfer', function (message) {
            this.messageFromA = message
        })
    }
    
  • 相关阅读:
    configure: error: invalid variable name: `'
    [bzoj2002][Hnoi2010]Bounce弹飞绵羊——分块
    [bzoj2049][Sdoi2008]Cave 洞穴勘测——lct
    [bzoj4765]普通计算姬——分块
    [bzoj4766]文艺计算姬——完全二分图生成树个数
    [bzoj2243][SDOI2011]染色——树链剖分+线段树
    [bzoj3306]树——树上倍增+dfs序+线段树
    [bzoj1977][BeiJing2010组队]次小生成树 Tree——树上倍增+lca
    [bzoj3697]采药人的路径——点分治
    小蒟蒻的天坑
  • 原文地址:https://www.cnblogs.com/my3306/p/9719661.html
Copyright © 2011-2022 走看看