栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > Vue.js

Vue.js父子组件和非父子组件间的传值通信

Vue.js 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Vue.js父子组件和非父子组件间的传值通信

[toc]

父子组件的传值通信父组件向子组件传值
  • 父组件:



data () {    return {
        parentMessage: "this is a message from parent"
    }
}
  • 子组件:

data () {
    props: ["message"]
}data () {
    props: {
        message: {
            type: String, //接收类型
            default: "this is the default value" // 默认值
        }
    }
}
子组件向父组件传值

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

  • 父组件:

data () {
    return {
        valueFromChild: "defaultValue"
    }
},
methods: {
    receive (valueFromChild) {
        this.valueFromChild = valueFromChild
    }
}
  • 子组件:



data () {    return {
        childValue: 'this is child Value'
    }
},
methods: {
    sendValueToParent () {        
        this.$emit('getChildValue', this.childValue)
    }
}
非父子组件之间的传值通信
  1. 创建 eventBus.js

import Vue from 'vue'var bus = new Vue()export default bus
  1. 组件 A

import eventBus from '.../eventBus.js'

data () {
    return {
        message: "message from A"
    }
},
methods: {
    sendMessageToB () {
        eventBus.$emit('transfer', this.message); 
    }
}
  1. 组件 B



import eventBus from '.../eventBus.js'data () {    return {
        messageFromA: "defaultValue"
    }
},created () {
    eventBus.$on('transfer', function (message) {
        this.messageFromA = message
    })
}



作者:沙海飞鱼
链接:https://www.jianshu.com/p/75ff1773ce41


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/241019.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号