安装
Vue2 对应 Vuex3,Vue3 对应 Vuex4,安装时需要注意自己使用的 Vue版本
安装最新版本
npm intall vuex
安装Vuex3指定版本
npm install vuex@3.x
使用
如图所示,在src目录下创建store文件夹,在store文件夹中创建index.js文件
在index.js文件中引入vuex,具体写法如下
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store=new Vuex.Store({
state:{
airItem:'aqi',
},
getters:{
airItem: state => state.airItem,
},
mutations:{
set_airItem:(state,airItem)=>{
state.airItem=airItem;
},
},
actions:{}
})
export default store
在main.js文件中引入store
代码如下图所示
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
将store添加到main.js中之后,就可以在vue组件中使用this.$store.getters.airItem
动态获取变量airItem的值,使用this.$store.commit('set_airItem','pm10')
改变变量airItem的值