我在Vue.js项目的main.js
中声明了一个全局变量。
Vue.prototype.$API = "myapihere"
我希望能够在任何地方使用它,并且通过 this.$API
正常工作。
但是在 Vuex 中它无法正常工作。
console.log(this.$API);
这里this.$API
是未定义的。
我如何在Vuex中使用我的$API
。
我在Vue.js项目的main.js
中声明了一个全局变量。
Vue.prototype.$API = "myapihere"
我希望能够在任何地方使用它,并且通过 this.$API
正常工作。
但是在 Vuex 中它无法正常工作。
console.log(this.$API);
这里this.$API
是未定义的。
我如何在Vuex中使用我的$API
。
Vue 2和Vuex 3解答
在store中,通过访问this._vm
可以访问Vue实例
const store = new Vuex.Store({
mutations: {
test(state) {
console.log(this._vm);
}
}
});
const app = new Vue(/* settings */); store:$app = app
,以便在存储初始化自己之后,提供自己的Vue实例引用来渲染我的应用程序。然后通过this.$app
从存储中访问根实例。 - ExcalibaardVue.prototype.$foo
在此版本中已被删除。我还发现,在我的VueX版本中没有this._vm
。store
上使用标准属性来设置它们。
main.js
:import store from './store/index';
import App from './App.vue';
// Load custom globals
import conf from '@/inc/myapp.config';
const app = createApp(App)
.use(store);
// Register globals in app and store
app.config.globalProperties.$conf = conf;
store.$conf = conf;
app.mount('#app');
我喜欢的是,我可以在store和组件中以相同方式访问全局变量。
在组件中:export default {
data() {
return {
};
},
created() {
console.log( this.$conf.API_URL );
},
}
...你可以通过相同的方式从actions、mutations和getters访问this.$conf.API_URL
。
一旦我找到了这个解决方案,我就不再需要从存储中访问整个Vue实例,但如果出于某些原因需要访问它,可以在main.js
中的相同位置分配store.$app = app
。
Pass down the property (or even access the _vm
property from inside Vuex) as an argument from a component
methods: {
this.$store.dispatch('someAction', this.$API)
}
Declare and export that same variable from another file and consume it from your main.js AND your Vuex file:
// api.js
export const API = "http://localhost:5000/api"
// main.js
import { API } from './api.js
...
Vue.prototype.$API = API
// store.js
import { API } from './api.js
// you can use API now!
使用this._vm
这是为什么
默认情况下,当您在vuex store
中访问this
时,它将指向store
,因此它会输出类似于这样的内容
所以在此之后,您会看到存储中有一个名为_vm
的东西,如下所示
因此,_vm
指向vue组件,因此要访问它,您需要使用this._vue
您可以更好地创建vue实例的getter
const store = new Vuex.Store({
getters: {
vue(state) {
return this._vm
}
}
});
//so you can use it across your store
store.getters.vue
//Note
//the above way of accessing getter works on non `namespaced` stores
this.$app
。相反,你可以使用 Vue Router 定义的 this.$router
。router.app = app;
,在 action 中,例如:let app = this.$router.app;
。
this
不是指 Vue 实例,所以它无法正常工作,请尝试使用this._vm
。 - Chris Lithis._vm
,在我的actions.js
文件中,this
是未定义的。 - secondmanthis
将指向你的 mutations 或 actions 所在的Vuex.Store
实例。但是在真实世界的应用中,这并不是一个常见的场景。当你在一个文件中有 200 个 actions 和 mutations 时,你的代码将会变得混乱且难以维护。因此,在最简单的应用程序中,这将起作用,但在一个相当大的应用程序中则不然。 - secondman