vue非父子組件間傳參問題
阿新 • • 發佈:2018-11-14
const 混亂 mit 傳參 影響 成本 導致 chang eno
最近在使用vue進行開發,遇到了組件之間傳參的問題,此處主要是針對非父子組件之間的傳參問題進行總結,方法如下:
一、如果兩個組件用友共同的父組件,即
FatherComponent.vue代碼
<template>
<child-component1/>
<child-component2/>
</template>
此時需要組件1給組件2傳遞某些參數,實現如下:
1、父組件給組件1綁定一個方法,讓組件1進行回調,組件2接收某個屬性,通過改變父組件的數據從而實現組件2的屬性值的更新,即
父組件
<child-component1 :callback="child1Callback" />
<child-component2 :props="child2Props" />
data () {
return {
child2Props: '';
}
}
child1Callback ([args...]) {
// 此處更新了父組件的data,使組件2的屬性prop改變
this.child2Props = [args...]
}
組件1
props: ['callback']
change () {
this.callback([args...])
}
2、通過bus進行實現,首先bus.js如下
const bus = new Vue()
export default bus
組件1
import bus from './bus'
methods: {
change () {
bus.$emit('callComponent2', [args...])
}
}
組件2
import bus from './bus' mounted () { bus.$on('callComponent2', function ([args...]) { // 做你想做的 }) }
3、利用vuex實現,創建store.js相當於某些全局變量,但是可以被vue檢測到變化
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
pageNo: 0
},
mutations: {
'change' (state, [args...]) {
state.pageNo++
}
}
})
export default store
項目入口js
import store from './store.js'
new Vue({
...
store: store
...
})
此時在任意vue文件都可以改變pageNo的值,並且會影響到所有使用了pageNo的組件,都會進行更新
childComponent1.vue
this.$store.commit('change')
childComponent2.vue
{{this.$store.state.pageNo}}
總結:
1、第一種比較繞,需要有共同的父組件,如果組件間層級太多,會導致代碼混亂,比較難維護。
2、第二種比較直觀,推薦使用,但是要理解,請仔細閱讀官方文檔
3、利用vuex在很多項目中都會顯得殺雞用牛刀,雖然更好理解,但是也帶來了學習成本,並且可能會有一些副作用,但是如果項目比較復雜,利用vuex更加直觀
綜合各種方法的優缺點,推薦使用第二種,項目過於復雜請使用第三種
如果有更好的方法,請留言指教,謝謝
原文地址:https://segmentfault.com/a/1190000012555128
vue非父子組件間傳參問題