Vue中组件的之间传值常用方法

一. 父子组件传值

1.props/$emit

Parent.vue

<template>
    <div>
        <h1>Parent</h1>
        <h3>{{msg}}</h3>
        <m-child :msg="'from Parent Msg'" @showMsg="getMsg"></m-child>
    </div>
</template>

<script>
    import MChild from './Child'
    export default {
        data() {
            return {
                msg: ''
            }
        },
        components: {
            MChild,
        },
        methods: {
            getMsg(val) {
                this.msg = val
            }
        },
    }
</script>
child.vue

<template>
    <div>
        <h3>Child</h3>
        <h3>{{ msg }}</h3>
        <button @click="sendMsg">点我</button>
    </div>
</template>

<script>
    export default {
        props: {
            msg: {
                type: String,
                default: ''
            },
        },

        methods: {
            sendMsg() {
                this.$emit('showMsg','I am from Child') 
            }
        },
    }
</script>

<style scoped>

</style>

2.this.$children / this.$parent

在父组件 Parent.vue 中调用子组件的data

mouted() {
    console.log(this.$children[0].msg)
}

注:msg 是子组件中 data 定义的属性名

子组件调用父组件过程一样

3.this.$refs

在父组件中定义子组件的ref属性

<m-child :msg="'from Parent Msg'" @showMsg="getMsg" ref="child"></m-child>

后调用

mounted () {
            // 调用 this.$children 传值
            console.log(this.$children[0])

            // 调用 this.$refs 与 上面 this.$children 等价
            console.log(this.$refs.child)
        },

二. 非父子组件中传值

1.事件总线

// 原理上是创建一个公共的js文件,专门用来传递信息

//1.创建bus.js
import Vue from 'vue'
// 非父子组件交互的公共js文件
export default new Vue;

// 在需要传递的地方引入
import bus from './util/bus'

// 传递信息
bus.$emit('msg',val)

//接受信息
bus.$emit('msg', val=>{
 console.log(val)   
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值