vuex的作用,vuex就是存储数据,类似于cookie,sessionStorage,localStorage将网页上是一些数据存储下来,以便于复用。
但是上面举了那么多的例子,为什么不用cookie,sessionStorage,localStorage,偏偏用Vuex?
当我满俩个组件都拥有一个共同的对象A,如果一个对象改变了对象A,我们需要另外一个对象也跟着变化的时候,这个时候我们就用到了vuex,正是这一点,其他的存储方式不能够比的。如图一图二所示
图1 图2
1、安装
npm install vuex --save
2、创建store.js
export default new Vuex.Store({
state: {
city: '上海'
},
mutations: {
changeCity (state, city) {
state.city = city
}
}
3、main.js引入
//vuex
import store from './store/store.js'
new Vue({
el: '#app',
router,
store: store,
components: { App },
template: '<App/>'
})
4、输入store.js的值
<div>{{this.$store.state.city}}</div>
<button @click="click(3)">提交</button>
5、方法里面修改store.js的值
click:function(value){
//axios存储
this.$store.commit('changeCity', value);
}
6、mutations里面修改storge的值
let defaultCity = '上海'
// 添加try防止用户本地缓冲异常或者隐身模式,导致异常
try {
if (localStorage.city) {
defaultCity = localStorage.city
}
} catch (e) {}
export default new Vuex.Store({
state: {
city: defaultCity
},
mutations: {
changeCity (state, city) {
state.city = city
try {
localStorage.city = city
} catch (e) {}
}
}
})