1、安装
//安装vuex
npm install vuex --save
在src目录下创建store文件夹,并创建index.js数据仓库
index.js
import Vue form 'vue'
import Vuex form 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
city: '杭州'
} //此处为数据
})
在main.js中引入
main.js
import Vue from 'vue'
import store form './store' //此处相当于'./store/index'
new Vue({
el: '#app',
store
})
2、读取数据
读取store中的数据(store文件中的数据可以在各个组件中读取)
<template>
<div>{{this.$store.state.city}}</div>
</template>
<script>
export default {
data () {
return {
city: this.$store.state.city
}
}
}
</scrtpt>
读取数据优化
<template>
<div>{{this.currentCity}}</div>
</template>
<script>
<!--mapState为vuex内部方法-->
import {mapState} from 'vuex'
export default {
data () {
return {
city: this.currentCity
}
},
computed: {
<!--通过扩展运算符对数据进行展开-->
<!--把vuex中的city属性映射到组件的computed属性currentCity中-->
...mapState({
currentCity: 'city'
})
}
}
</scrtpt>
3、改变store中的数据
组件中
<script>
export default {
data () {
city: '上海'
},
mounted () {
//派发一个changeCity并传递新的数据
this.$store.dispatch('changeCity',this.city);
}
}
</scrtpt>
store中的index.js
import Vue form 'vue'
import Vuex form 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
city: '杭州'
}, //此处为数据
actions: {
//此处的changeCity为组件中派发的事件
changeCity (ctx, city) {
//此处能读取到组件中传过来的city值
//然后需要把city值写入store中
ctx.commit('changeCity', city)
}
},
mutations: {
//此处写actions中触发的事件
changeCity (state, city) {
//赋值state
state.city = city
}
}
})
步骤:
组件中调用store的dispatch方法触发actions,actions触发后通过调用commit触发mutations对store中的数据重新赋值。其中actions步骤可省略,直接在组件中调用this.$store.commit方法
3、防止页面刷新数据丢失,需要用localStorage对数据进行存储
store中index.js
import Vue form 'vue'
import Vuex form 'vuex'
Vue.use(Vuex)
//此处是为了防止某些浏览器关闭了localStorage功能而导致抛出异常的兼容
let defaultCity = '杭州'
try {
if (localStorage.city) {
defaultCity = localStorage.city
}
} catch (e) {}
export default new Vuex.Store({
state: {
city: defaultCity
}, //此处为数据
actions: {
//此处的changeCity为组件中派发的事件
changeCity (ctx, city) {
//此处能读取到组件中传过来的city值
//然后需要把city值写入store中
ctx.commit('changeCity', city)
}
},
mutations: {
//此处写actions中触发的事件
changeCity (state, city) {
//赋值state
state.city = city
//设置localStorage值
try {
localStorage.city = city
} catch (e) {}
}
}
})
4、方法的拆分
对于复杂的store可以拆分成不同的文件,可以拆分成state.js、actions.js和mutations.js,然后在index.js中引入这些文件
index.js
import Vue form 'vue'
import Vuex form 'vuex'
import state from './state'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
state: state,
actions: actions,
mutations: mutations
})
例如state.js
let defaultCity = '杭州'
try {
if (localStorage.city) {
defaultCity = localStorage.city
}
} catch (e) {}
export default {
city: defaultCity
}
5、使用getter对vuex中的state数据进行重新计算返回计算后的结果
getter相当于组件中的computed,从而减少每个组件计算的代码冗余
getters: {
dobuleCity: (state) {
return state.city + ' ' + state.city
}
}
6.使用module可以把vuex分成一个个模块,从而减少单个文件过于庞大
其中state、actions、mutations都可以拆分
高级用法传送门