我正在尝试为Vue创建一个mixin,它基本上创建了一个属性passthrough链。我会澄清应该更清楚的事情;
假设我有3个组件; A,B和C.
A& B都是名为“content-pane”的相同组件(请参阅下面的模板代码)。
<div class="pane-wrapper">
<div class="content-pane" :class="{'is-hidden' : !active}" :content="name">
<div class="card white">
<div class="card-title grey darken-3">
<h1 class="white-text">{{ label }}</h1>
</div>
<div class="card-content white">
<component
:is = "type"
:routes = "routes"
:passthrough = "passthrough"
keep-alive
></component>
</div>
</div>
</div>
<content-pane
v-for="(pane, key) in children"
:key = "key"
:label = "pane.label"
:name = "pane.name"
:active = "true"
:type = "pane.type"
:routes = "pane.routes"
></content-pane>
</div>
C是一个动态组件,意味着它是可互换的,可以是任何组件。
现在我希望能够从组件A中的组件C访问某些数据,为此我尝试创建一个以动态方式提供数据属性的mixin来执行此操作:
<script>
export default {
name: 'passthrough',
props: {
passthrough : {
type : Object
}
},
data ()
{
return {
// This object allows you to
// update the parent.
passthroughModifier : {
// We use the data object inside the
// original object because Vue doesn't
// want to detect direct prop changes
// when they are added dynamically
// into the root object...
data : {}
}
}
},
methods : {
/**
* This function fires an emit event.
*/
emitUpdate ()
{
this.$emit('passthrough-update', this.passthroughModifier);
}
},
watch : {
/**
* Emit an event once the passthrough
* property has been changed.
* We need to use a deep watcher.
*/
'passthroughModifier' : {
handler : function (val) {
this.emitUpdate();
},
deep: true
}
},
created ()
{
// Allow access to the instance
// inside the iteration.
let _that = this;
// Attach a listener for the passthrough update
// which will walk through all the keys in the
// data object and hard-set these locally.
this.$on('passthrough-update', function (data) {
Object.keys(data).forEach(function (index) {
_that.passthroughModifier[index] = data[index];
});
});
}
}
除了收听由$ .passthroughModifier观察者触发的'passthrough-update'事件外,一切正常。
因此;当组件C更新其$ .passthroughModifier.data时,会发出该事件,但组件B无法捕获此事件。
我曾尝试在mixin的created()
方法中监听此事件(请参阅上面的代码),但似乎事件仅在触发事件的组件中被捕获。因此,组件C将触发事件,组件C将侦听其自己的事件。
我希望有人能够告诉我这实际上是否可行,以及如果可能的话,我做错了。