很多人不明白,this.$store与store的区别
简单来说,如果你在根组件下注入了store那么所有的.vue文件里使用就可以直接用 this.$store.xxxx
;而在js文件里面如果想要使用store,就必须先引入import store from '@/store'
然后使用store.xxx
,因为js里面是打印不出来this.$store
的
vue官网是这么说的:
为了在 Vue 组件中访问 this.$store property,你需要为 Vue 实例提供创建好的 store。Vuex 提供了一个从根组件向所有子组件,以 store 选项的方式“注入”该 store 的机制:
//main.js
import store from './store'
new Vue({
el: '#app',
store,
})
而store文件里面的内容如下:
![](https://img.haomeiwen.com/i5418302/0ca7aa9162ea3f57.png)
image.png
//store/index.js文件
import Vue from 'vue';
import Vuex from 'vuex';
import user from './modules/user.js';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
user
},
getters
});
//modules/user.js文件
const user = {
state: {
userInfo: {},
},
actions: {
},
mutations: {
}
}
export default user
这样就把store注入到了所有子组件
再测试下js文件使用store的问题:新建了一个文件src/test.js,在main.js里面引入此js;
// src/test.js文件
console.log(this.$store)
报错如下:
![](https://img.haomeiwen.com/i5418302/cb54eff23dbbd729.png)
image.png
又将内容改成如下:
// src/test.js文件
import store from './store/';
console.log(store)
console.log(this)
console.log(this.$store)
控制台返回值中,this与 this.$store都获取不到;如下
![](https://img.haomeiwen.com/i5418302/cc95a130db177edd.png)
image.png
总结:
vue文件中使用store直接用this.$store.xxxx即可,因为在main.js里面注入store之后,给所有的vue子组件都注入了store(组件是指.vue文件,不包括js文件,所以js必须单独引用)
而所有的js文件要使用store必须引入才能使用,而且js文件始终打印不出来this.$store
网友评论