Vue.js VueJS-访问装载的内部存储数据
我无法理解以下内容:Vue.js VueJS-访问装载的内部存储数据,vue.js,vuejs2,Vue.js,Vuejs2,我无法理解以下内容: mounted() { this.$store.dispatch( "fetchUsers" ); var currentName = this.$store.state.globalCompanies.currentName; console.log(currentName); }, 我有一个存储,其中包含应用程序所需的变量。特别是,有一个globalCompanies存储: globalCompanies: { current: [],
mounted() {
this.$store.dispatch( "fetchUsers" );
var currentName = this.$store.state.globalCompanies.currentName;
console.log(currentName);
},
我有一个存储
,其中包含应用程序所需的变量。特别是,有一个globalCompanies
存储:
globalCompanies: {
current: [],
all: [],
currentName: "",
}
在另一个组件中,我要执行以下操作:
mounted() {
this.$store.dispatch( "fetchUsers" );
var currentName = this.$store.state.globalCompanies.currentName;
console.log(currentName);
},
然而,这只是显示为空。我知道值在那里,因为我有computed
,它返回currentName
,并且它在视图内部工作良好。它只是不喜欢它在安装的组件中
我哪里出了问题?我能做些什么来解决这个问题?我真的需要捕获公司名称,以便将其用于一些实时事件 根据我们的讨论结果: 在问题中,在组件的
mounted
钩子中访问的Vuex状态值返回空值,因为它是在异步操作中设置的,在执行mounted
之前不会解析
当Vuex中的异步操作解析为值时,需要触发某些函数时,可以使用计算属性上的watch
来实现该函数,该属性将从Vuex状态返回一个值。当存储区中的值发生更改时,computed属性将反映这些更改,并执行watch
listener:
const store=新的Vuex.store({
声明:{
全球公司:{
测试:空
}
},
突变:{
setMe:(状态,有效载荷)=>{
state.globalCompanies.test=有效载荷
}
},
行动:{
获取:({commit})=>{
设置超时(()=>{
commit('setMe','My text is here!')
}, 300)
}
}
})
新Vue({
el:“#应用程序”,
商店,
计算:{
cp:function(){//computed属性将在异步调用解析时更新
返回此。$store.state.globalCompanies.test;
}
},
注意:{//注意这里的变化
cp:函数(newValue、oldValue){
//在此应用您的逻辑,例如调用侦听器函数
log('was:',oldValue,'now:',newValue)
}
},
安装的(){
此.$store.dispatch('fetch');
//console.log(this.cp,this.$store.state.globalCompanies.test);//null
//var cn=this.$store.state.globalCompanies.test;//null
//console.log(cn)//null
}
})
{{cp}}
VueJS-访问挂载内存中的存储数据
遇到这个问题,结果是范围问题
商店:
export default () => {
items:[],
globalCompanies:{
current:[],
all:[],
currentName: "Something"
},
ok: "Here you go"
}
export default {
getGlobalCompanies(state){
return state.globalCompanies;
}
}
获取者:
export default () => {
items:[],
globalCompanies:{
current:[],
all:[],
currentName: "Something"
},
ok: "Here you go"
}
export default {
getGlobalCompanies(state){
return state.globalCompanies;
}
}
已安装:此功能有效
mounted() {
// Initialize inside mounted to ensure store is within scope
const { getters } = this.$store;
const thisWorks = () => {
const globalCompanies = getters.getGlobalCompanies;
}
},
这很糟糕:到达安装范围之外的商店
mounted() {
function ThisDontWork() {
const { getters } = this.$store; // this.$store == undefined
}
ThisDontWork();
},
是由此异步调用“fetchUsers”设置的
state.globalCompanies.currentName
。@wostex否,是由加载页面时发生的另一个异步调用设置的。它位于另一个组件中尝试检索计算属性中的currentName
,正如您所说,它在那里工作,并在mounted()中使用该计算属性hook@VAMSI奎师那-试过这个。您无法在mounted()
中访问它,它只显示一个空对象。但是,在视图中,我有以下内容:Search{{{this.current}
,它显示了正确的值。但是执行console.log(this.current)代码>只是在mounted()
中显示一个空对象:(@Phorce,显然mounted
钩子在异步调用解决之前运行。计算属性处理这个问题:当数据到达时,计算属性也会更新。但是在mounted
中,您会得到空值,因为它还不在那里(mounted只运行一次)@rupshterase是的,请仔细阅读答案。您可以使用watch
并在回调中操纵值。watch-就是这样!谢谢!