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)   
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章