vue 2コンポーネント間の値伝達
1767 ワード
vue 2バージョンのコンポーネント間の値伝達の簡単な統合:親コンポーネント=』サブコンポーネント:propsおよびrefs 子コンポーネント=』親コンポーネント:カスタムイベント 兄弟コンポーネント:共通の祖先を介してp a r e n tまたはparentまたはparentまたはroot をブリッジする祖先=>子孫provide/inject 子孫=』祖先再帰はroot に配布された.任意の2つのコンポーネント間のイベントバスとvuexイベントバス
3,4,5,6はすべて直接$rootを使うことができます
-
props: { msg: String }
//parent
this.$ref.helloWorld.msg
//child
this.$emit('send', msg)
//parent
// brother1
this.$parent.$on('foo', handle)
// brother2
this.$parent.$emit('foo')
// ancestor
provide() {
return {
msg: 'welcome'
}
}
// descendant
inject: ['msg']
// dispatch ,
function dispatch(eventName, data) {
let parent = this.$parent
while (parent) {
// $emit
parent.$emit(eventName,data)
//
parent = parent.$parent
}
}
// ,HelloWorld.vue
{{ msg }}
// App.vue
this.$on('hello', this.sayHello)
class EventBus {
constructor() {
this.callbacks = {}
}
$on(name, fn) {
this.callbacks[name] = this.callbacks[name] || []
this.callbacks[name].push(fn)
}
$emit(name) {
let fns = this.callbacks[name]
if(fns) {
fns.map(fn => fn())
}
}
}
//
main.js
Vue.prototype.$bus = new EventBus()
this.$bus.$on('send', handleFn)
this.$bus.$emit('send')
vuex: store, vue ,
3,4,5,6はすべて直接$rootを使うことができます