1 , 安装
(1):直接下载
https://unpkg.com/vuex@2.0.0
(2):npm
npm install vuex --save ;
2 , Vuex的创建
let store = new Vuex.Store({
state:{
<!--数据-->
} ,
getters:{
<!--数据处理-->
} ,
mutations:{
<!--方法,不支持异步-->
} ,
actions:{
<!--方法,支持异步-->
} ,
modules:{
<!--模块-->
}
}) ;
<!--导出-->
export default store ;
3 , Vuex的结构树
store
index.js<!-- 用来组装模块和导出store -->
state.js<!-- 用来存放数据 -->
getters.js <!-- 用来计算数据 ,
外部调用方法 this.$store.getters.fn -->
mutations.js <!-- 同来存放方法 ,
外部调用方法 this.$store.commit(fn)
但不支持异步操作 ;
-->
actions.js <!-- 和mutations差不多
外部调用方法 this.$store.dispatch(fn)
支持异步操作
-->
modules
m1 <!-- 模块1 -->
m2 <!-- 模块2 -->
4 , 结构树的实例
(1):state的实例
//存放数据
const state = {
name:'123' ,
age:24 ,
} ;
export default state ;
(2):getters的实例
const getters = {
getName(state){
return state.name ;
} ,
getAge(state){
return state.age ;
}
} ;
export default getters ;
(3):mutations的实例
//各种方法
export default {
setName(state,val){
state.name = val ;
} ,
setAge(state,val){
state.age = val ;
}
}
(4):actions的实例
export default {
setAge(state){
state.commit('setAge',1000) ;
}
}
----------------------------------------
export defaulte {
setAge({ commit }){
commit('setAge',1000)
}
}
5 , 挂载到main.js中
import store from './store/index.js'
let app = new Vue({
el:'#app',
store ,
})
6 , 关于mapState,mapGetters、mapActions、mapMutations
<!--
由于每次调用vuex中的数据或者方法都要使用$store.state.数据
比较麻烦,因此使用mapState等
-->
在vue组件中引入mapState
import {mapState,mapGetters,mapActions,mapMutations} from 'vuex' ;
在vue组件中的computed或者methods中使用...mapState
computed:{
<!--
这样子就可以直接用name和age来代替
$store.state.name和$store.state.age
-->
...mapState([
'name',
'age' ,
])
} ,
methods:{
<!--
点击的时候可以直接使用fn(val)
button @click='fn(val)' ;
fn就是this.$store.commit('setName') ;
-->
...mapMutations({
fn:'setName' ,
})
}