1、下载安装
2、store文件夹下创建模块
3、index.js中是入口文件,代码如下:
import { createStore } from "vuex";
//分别创建的各个模块js
import * as actions from './actions'
import mutations from './mutations'
//暴露出去
export default createStore({
state: {
name:'张三',
age:'18',
sex:'男',
},
mutations,
actions,
});
4、mutation-types.js中声明常量暴露
export const SET_NAME = 'SET_NAME'
export const SET_AGE = 'SET_AGE'
export const SET_SEX = 'SET_SEX'
5、mutations.js中引入类型文件,当然你不习惯这种写法也可以不这么写,这么写的话大型项目方便管理。
//类型模块
import * as types from "./mutation-types";
//改变数据
export default {
[types.SET_NAME](state, data) {
state.name = data;
},
[types.SET_AGE](state, data) {
state.age = data;
},
[types.SET_SEX](state, data) {
state.sex = data;
},
};
6、actions.js中去调用mutaitions.js中方法
import * as types from './mutation-types'
//去触发mutation里边的方法改变数据
export const changeAge = ({commit}, data) => {
commit(types.SET_AGE, data)
}
7、页面中使用,代码如下:
<template>
<div class="test">
<h1>{{title}}</h1>
<p>{{$store.state.name}}</p>
<p>{{$store.state.age}}</p>
<button @click="changeName">改变姓名</button>
<button @click="changeAge">改变年龄</button>
</div>
</template>
<script>
import * as types from "../store/mutation-types"
export default {
name: "Test",
data(){
return{
title:'111'
}
},
methods:{
//mutations.js方法直接触发
changeName(){
this.$store.commit(types.SET_NAME,'李四')
},
//actions.js中方法触发mutations.js中的方法
changeAge(){
this.$store.dispatch('changeAge',20)
}
},
mounted(){
}
};
</script>
以上是分模块使用vuex方法。