Javascript 访问js文件中的vuex存储
就像在main.js中一样,我尝试从助手函数文件访问我的存储:Javascript 访问js文件中的vuex存储,javascript,vue.js,vuex,Javascript,Vue.js,Vuex,就像在main.js中一样,我尝试从助手函数文件访问我的存储: import store from '../store' let auth = store.getters.config.urls.auth 但它记录了一个错误: 未捕获的TypeError:无法读取未定义的属性“getter” 我试过了 this.$store.getters.config.urls.auth 同样的结果 商店: //Vuex import Vue from 'vue' import Vuex from 'v
import store from '../store'
let auth = store.getters.config.urls.auth
但它记录了一个错误:
未捕获的TypeError:无法读取未定义的属性“getter”
我试过了
this.$store.getters.config.urls.auth
同样的结果
商店:
//Vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
config: 'config',
},
getters: {
config: state => state.config
},
});
export default store
如何使我的存储区在组件之外可用?以下内容对我很有用:
import store from '../store'
store.getters.config
// => 'config'
// app.js
import store from "./store/index"
const app = new Vue({
el: '#app',
store, //vuex
});
window.App = app;
// inside your helper method
window.App.$store.commit("commitName" , value);
在你的导入上放上括号,它应该会起作用
import { store } from '../store'
尝试导入特定的js文件
import store from '../store/index.js'
使用这种方法对我很有效:
import store from '../store'
store.getters.config
// => 'config'
// app.js
import store from "./store/index"
const app = new Vue({
el: '#app',
store, //vuex
});
window.App = app;
// inside your helper method
window.App.$store.commit("commitName" , value);
这在2021年对我起了作用
我尝试了很多不同的方法,看起来,至少在VUE3中,这是可行的。以下是一个示例商店:
export default {
user: {
bearerToken: 'initial',
},
};
这是我的Getters
文件:
export default {
token: (state) => () => state.user.bearerToken,
};
在.js
文件中,将页面添加到存储\索引.js
文件中
import store from '../store';
要访问getter,请记住它是一个函数(当您使用mapGetters
时,它可能看起来有所不同)
国家更直接:
console.log('Checking the state:', store.state.user.bearerToken);
如果您使用的是带名称空间的模块,您可能会遇到与我在尝试从商店检索项目时遇到的相同的困难 对您来说,可能的解决方法是在调用getter时指定名称空间(下面的示例)
import store from'../your path to your store file/store.js'
console.log(store.getter。['module/module_getter']);
//比如说
console.log(store.getters.[auth/data']);
商店未定义。编辑对我有效。刚刚在我的回购协议上试过。是的,如果您在Vue之外访问store,您必须使用getters
。是的,只要看看它,它应该可以工作,但由于一些非常奇怪的原因,它不工作。我会仔细检查您的项目中store.js
的路径是否正确。但这可能会导致意外行为。例如,对于我来说,当用户第一次登录时,这只会在.js文件中产生未定义的内容,但Vuex显示它已明确定义。我看到了一些相关问题,这是由于新版本的旧语法造成的。我认为给出的答案是在最新版本中检查过的。编写一个纯函数,将store
getter作为函数参数,怎么样?然后在Vue组件中使用函数时,将存储
传递给该函数。为什么要放括号?它有一个默认的导出。javascript console.log(store.getters)//返回vuex中的所有getter,在调试时可能会有所帮助代码>