vue-cli vuex
官网:https://vuex.vuejs.org/
基本图解
使用:
一:安装vuex
cnpm install vuex --save
二:创建新文件夹
src文件下面创建store文件夹,store文件夹中新建index.js
index.js中写:
import Vue from ‘vue’
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.store({
state:{
city:'北京'
},
actions:{
changeCity(ctx,city){
ctx.commit('changeCity',city)
}
},
mutations:{
changeCity(state,city){
state.city=city
}
}
})
三:main.js中
import store from './store'
new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
四:哪个页面中使用了vuex,这里读取到上面默认的北京
<p>{{this.$store.state.city}}</p>
五:实现这个值再某一处做了修改,其他用到这个的地方也修改
handleCity(city){ this.$store.dispatch("changeCity",city); },
到这步要在store->index.js添加actions、mutations
在这里可以省略action一步,可以这样做
handleCity(city){ this.$store.commit("changeCity",city); },
这里在store->index.js添加mutations就可以了