详解vuex数据传输的两种方式及this.$store undefined的解决办法
这个问题很乌龙,但也很值得记录一下,原因是main.js中importstore时将store的首字母写成了大写.
问题版本的如下所示:
importStorefrom'./store'
我大概看了一下,vue似乎不支持在import部分包含带首字母大写的变量,所有import进来的对象必须要小写,我试过把router改成Router,发现路由部分也会受影响.
这种方式是典型的将vuex值及其中的方法暴露给所有的组件使用,即将vuex视作一个"全局变量",但vuex也可以仅提供给部分组件,即谁想用,在谁的script中import这个vuex对象.
第一种方式-将vuex提供给所有组件(即在main.js中注册)
//main.js importVuefrom'vue' importAppfrom'./App' importstorefrom'./store' importrouterfrom'./router' importElementUIfrom'element-ui' import'element-ui/lib/theme-chalk/index.css' Vue.config.productionTip=false Vue.use(ElementUI) newVue({ router, store, render:h=>h(App) }).$mount('#app')
//store/index.js importVuefrom"vue"; importVuexfrom"vuex"; Vue.use(Vuex); conststore=newVuex.Store({ state:{ n:101 } }) exportdefaultstore
//view部分,即真正的可视化的部分,这个任何一个组件都可以{{n}}
第二种方式,仅部分组件可使用vuex
//main.js-去掉了store的声明 importVuefrom'vue' importAppfrom'./App' importrouterfrom'./router' importElementUIfrom'element-ui' import'element-ui/lib/theme-chalk/index.css' Vue.config.productionTip=false Vue.use(ElementUI) newVue({ router, render:h=>h(App) }).$mount('#app')
//store/index.js-这个文件和上面的一样 //想要使用vuex数据的组件.注意,此时$store是无效的,所以只能通过store.state.n来获取{{n}}