从组件 VM 中的主要 Vue.js 实例访问变量
Accessing variable from main Vue.js instance in component VM
这是一个非常简单的 Vue 应用程序,它将 prop 从主 VM 传递到组件。这个值是我实际应用中通过vue-resource抓取的。
https://jsbin.com/tazuyupigi/1/edit?html,output
当然可以,但我很难从组件 VM 本身访问此值。
https://jsbin.com/hurulavoko/1/edit?html,output
如您所见,我的警报显示未定义。我怎样才能解决这个问题?似乎是执行顺序的问题,但使用 compiled()
或 created()
代替 ready()
没有区别。
执行顺序有问题。主 Vue 实例不是 "ready" 直到它里面的东西被编译。这包括 hello
组件。
如果您需要在使用前了解 bar
是否已设置,您可以通过多种方式进行监控。您可以 $broadcast
parent 中的事件让 child 知道 bar
已加载。或者您可以在 child 组件中使用 watch
函数在更新 bar
时进行更改。
如果您在 created()
中 $set
bar
,您的示例确实有效,但是对于 vue-resource
,您无论如何都会有延迟,因此您需要考虑因为 greeting
在 child 的 ready()
函数期间不会准备好。您要么必须设计 DOM 结构来处理 greeting
可能是 undefined
的事实,要么必须使用事件或 watch
函数来等待自己去吧。
示例$broadcast
:
Vue.component('hello', {
template: 'From hello tag: {{ greeting }}',
props: ['greeting'],
ready: function() {
},
events:{
'bar-ready':function(){
alert(this.greeting)
}
}
});
new Vue({
el: '#app',
created: function() {
this.$http.get('/path')
.then(function(response){
this.$set('bar',response.data);
this.$broadcast('bar-ready')
}.bind(this))
}
});
$broadcast
文档:https://vuejs.org/api/#vm-broadcast
这是一个非常简单的 Vue 应用程序,它将 prop 从主 VM 传递到组件。这个值是我实际应用中通过vue-resource抓取的。
https://jsbin.com/tazuyupigi/1/edit?html,output
当然可以,但我很难从组件 VM 本身访问此值。
https://jsbin.com/hurulavoko/1/edit?html,output
如您所见,我的警报显示未定义。我怎样才能解决这个问题?似乎是执行顺序的问题,但使用 compiled()
或 created()
代替 ready()
没有区别。
执行顺序有问题。主 Vue 实例不是 "ready" 直到它里面的东西被编译。这包括 hello
组件。
如果您需要在使用前了解 bar
是否已设置,您可以通过多种方式进行监控。您可以 $broadcast
parent 中的事件让 child 知道 bar
已加载。或者您可以在 child 组件中使用 watch
函数在更新 bar
时进行更改。
如果您在 created()
中 $set
bar
,您的示例确实有效,但是对于 vue-resource
,您无论如何都会有延迟,因此您需要考虑因为 greeting
在 child 的 ready()
函数期间不会准备好。您要么必须设计 DOM 结构来处理 greeting
可能是 undefined
的事实,要么必须使用事件或 watch
函数来等待自己去吧。
示例$broadcast
:
Vue.component('hello', {
template: 'From hello tag: {{ greeting }}',
props: ['greeting'],
ready: function() {
},
events:{
'bar-ready':function(){
alert(this.greeting)
}
}
});
new Vue({
el: '#app',
created: function() {
this.$http.get('/path')
.then(function(response){
this.$set('bar',response.data);
this.$broadcast('bar-ready')
}.bind(this))
}
});
$broadcast
文档:https://vuejs.org/api/#vm-broadcast