版本說明:vue-cli:3.0
主要分為兩類:
1.父子組件間的傳值
2.非父子組件間的傳值
1.父子組件間傳值
父組件向子組件傳值
第一種方式:
props
父組件嵌套的子組件中,使用v-bind:msg=‘xxxx’進行對象的綁定,子組件中通過定義props接收對應的msg對象如圖
父組件代碼
<template> <div> <!-- 注意 :msg 后面是一個對象,值是字符串時,需要寫冒號,如果省略:就是一個字符串 --> <!-- <m-child msg="from Parent msg" ></m-child> --> <m-child v-bind:msg="'from Parent msg'" ></m-child> </div> </template> <script> // 引入子組件 import MChild from './Child' export default { data () { return { msg: '' } }, components: { MChild, },
子組件代碼
<template> <div> <h5>{{msg}}</h5> </div> </template> <script> export default { // 要接受父組件傳遞的參數 props: { msg: { type: String, default: '' }, },
第二種方式:
使用$children獲取子組件和父組件對象
父組件代碼:
this.msg2=this.$children[0].msg
第三種方式:
使用$ref獲取指定的子組件
父組件代碼:
this.c2P=this.$refs.child.msg33
子組件向父組件傳值
第一種方式:
使用$emit傳遞事件給父組件,父組件監聽該事件
子組件代碼
<button @click="pushMsg()"></button> methods: { pushMsg() { this.$emit("showMsg", "這是子組件===>父組件的值"); } },
父組件代碼
<m-child v-bind:msg="p2C" @showMsg='getChild' ref='child'></m-child> methods: { getChild(val) { this.msg=val }, }
第二種方式:
使用$parent.獲取父組件對象,然后再獲取數據對象
子組件代碼
mounted() { this.msg22 = this.$parent.msg2; }
二.非父子組件間傳值
1.事件總線
原理上就是建⽴立⼀一個公共的js⽂文件,專⻔門⽤用來傳遞消息
bus.js
import Vue from 'vue' export default new Vue
在需要傳遞消息的地⽅方引⼊入
mport bus from './util/bus'
methods: {
passMsg () {
bus.$emit('msg', 'i am from app')
}
},
傳遞消息,在需要接受消息的地方使用bus.$on接受消息
mounted () { bus.$on('msg', (val) => { this.childMsg = val });
2.$sttrs/listeners 用於多級組件間傳值的問題
解決多級組件間傳值的問題
$attr 將⽗父組件中不不包含props的屬性傳⼊入⼦子組件,通常配合 interitAttrs 選項
組件A傳遞到組件C,使用組件B作為橋梁A-B-C
組件A
<template> <div id="app"> <!-- this is app --> <m-parent :msg="a" :msgb="b" :msgc="c"></m-parent> </div> </template>
組件B
<template> <div> <m-child v-bind="$attrs"></m-child> </div> </template>
組件C 注意:如果組件C中有props屬性接受的對象的化,組件A傳遞的對象就會被自動過濾掉
props: {
msg: {
type: String,
default: ''
},
}
mounted () { console.log('attrs',this.$attrs) }
一起使用。
如果不不想在dom上出現屬性,可設置interitAttrs: false
$listeners監聽⼦子組件中數據變化,傳遞給⽗父組件
3.vuex