1、Vuex分成五个部分:
State:单一状态树,共同维护的一个状态,state里面可以是很多个全局状态
Getters:状态获取,获取数据并渲染
Mutations:触发同步事件,处理数据的唯一途径,state的改变或赋值只能在这里
Actions:提交mutation,数据的异步操作
Module:将vuex进行分模块
2、使用步骤
2.1 安装
npm install vuex -S
2.2 创建store模块,分别维护state/actions/mutations/getters
store文件夹
index.js
state.js
actions.js
mutations.js
getters.js
2.3 在store/index.js文件中新建vuex的store实例,并注册上面引入的各大模块
除了index.js以外其他四个js文件都需要引入下面这个模块
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
const store = new Vuex.Store({
state,
getters,
actions,
mutations
})
export default store
2.4 在main.js中导入并使用store实例
main.js
import store from './store'
new Vue({
el: '#app',
router,
store, //在main.js中导入store实例
components: {
App
},
template: '<App/>',
data: {
}
})
2.5 state.js
export default{
//定义变量,名字自定义
htname:'aaa', //后面基本上用的是这个变量
hhname:'bbb',
}
2.6 mutations.js
export default {
sethtname: (state, payload) => {
state.htname = payload.htname;
},
}
2.7 action.js
export default {
sethtnameAsync: (context, payload) => {
console.log('哦哦哦');
setTimeout(() => {
console.log('嗯嗯嗯');
context.commit('sethtname', payload);
}, 3000);
console.log('哈哈哈');
},
doAjax:(context, payload) => {
//vuex是不能被vue实例的
let _this =payload._this;
let url = this.axios.urls.SYSTEM_USER_DOLOGIN;
// let url = 'http://localhost:8080/T216_SSH/vue/userAction_login.action';
console.log(url);
_this.axios.post(url,{}).then((response) => {
console.log('doAjax............');
console.log(response);
}).catch((response)=>{
console.log(response);
});
},
}
2.8 getters.js 获取数据并且渲染
export default{
gethtname: (state) => {
return state.htname;
}
}
2.9 显示页面VuePage1.vue
<template>
<div>
<h2>第一个vuex页面:</h2>
<h3>{{ht}}</h3>
<button @click="hscht">换诗词</button>
<button @click="hschtAsync">一个月后换诗词</button>
<button @click="doAjax">测试vuex中使用ajax</button>
</div>
</template>
<script>
export default{
data(){
return{
};
},
methods: {
hscht() {
this.$store.commit('sethtname',{
htname:'bbb',
});
},
hschtAsync() {
this.$store.dispatch('sethtnameAsync',{
htname:'ccc',
});
},
doAjax(){
this.$store.dispatch('doAjax',{
_this:this,
});
}
},
computed: {
ht() {
// return this.$store.state.htname; //不推荐这种方式
return this.$store.getters.gethtname;
}
},
}
</script>
<style>
</style>