VueJS - 组件如何获取全局数据项?
VueJS - how component gets global data item?
我有这样的代码:
Vue.component("sample", {
inherit: true,
template: "#sample",
props: {
active : "active",
...
},
methods: {
forceChangeActive: function(){
var activeItem = this.$parent._data.active;
var modalSetup = this.$parent._data.showModal;
console.log("1.before function", this.$parent._data);
this.$parent.$options.methods.baseAction(activeItem, modalSetup);
console.log("2.before function", this.$parent._data);
});
}
});
new Vue({
el: "#app",
data: {
active: 0,
showModal: false,
...
},
methods: {
baseAction: function(activeItem, modalSetup){
console.log("3.modal", modalSetup, "activeItem": activeItem);
modalSetup = true;
activeItem = 2;
console.log("4.modal", modalSetup, "activeItem": activeItem);
}
}
});
新Vue中有active和showModal数据变量。现在,如果我使用 this.active 或 this.showModal,我将对两者都不确定。
控制台输出为:
- before function Object { active=0, showModal=false }
- modal false, activeItem 0
- modal true, activeItem 2
- before function Object { active=0, showModal=false }
如何在新 Vue 或组件中更改变量的值?
inherit:true
已弃用。
您需要使用属性将 active
和 showModal
显式传递给 child 组件。您可以使用 .sync
来确保它们也被共享回 parent:
<sample :active.sync="active" :show-modal.sync="showModal"></sample>
我有这样的代码:
Vue.component("sample", {
inherit: true,
template: "#sample",
props: {
active : "active",
...
},
methods: {
forceChangeActive: function(){
var activeItem = this.$parent._data.active;
var modalSetup = this.$parent._data.showModal;
console.log("1.before function", this.$parent._data);
this.$parent.$options.methods.baseAction(activeItem, modalSetup);
console.log("2.before function", this.$parent._data);
});
}
});
new Vue({
el: "#app",
data: {
active: 0,
showModal: false,
...
},
methods: {
baseAction: function(activeItem, modalSetup){
console.log("3.modal", modalSetup, "activeItem": activeItem);
modalSetup = true;
activeItem = 2;
console.log("4.modal", modalSetup, "activeItem": activeItem);
}
}
});
新Vue中有active和showModal数据变量。现在,如果我使用 this.active 或 this.showModal,我将对两者都不确定。 控制台输出为:
- before function Object { active=0, showModal=false }
- modal false, activeItem 0
- modal true, activeItem 2
- before function Object { active=0, showModal=false }
如何在新 Vue 或组件中更改变量的值?
inherit:true
已弃用。
您需要使用属性将 active
和 showModal
显式传递给 child 组件。您可以使用 .sync
来确保它们也被共享回 parent:
<sample :active.sync="active" :show-modal.sync="showModal"></sample>