-
基本概念
vuex
可以理解为整个Vue程序
中的全局变量,但他和以前概念中的全局变量又有所不同,他也是响应式的,而且,你不能直接修改vuex中的变量,只能通过显式地commit=>mutation
来进行数据的改变。
-
五大模块
-
State => state里面存放的是变量,如果你要注册全局变量,写这里
-
Getter => getters相当于是state的计算属性,如果你需要将变量的值进行计算,然后输出,写这里
-
Mutation => 修改store中的变量的方法,如果你要改变变量的值,就写这里
-
Action => actions提交的是mutations,相当于就是改变变量的方法的重写,但是,actions是可以进行异步操作的
-
Module => 将整个Vuex模块化,主要的特点就是namespaced,所有的访问都要经过命名空间
-
基本定义
首先在src
文件目录下新建store
文件夹,在store
文件夹中新建module
文件夹以及index.js
,然后在module
中新建自己的功能模块的js文件,例如我这边新建了一个user.js
,专门存放用户相关的全局变量,所以目录如下
├─ src //主文件
| ├─ store //vuex全局变量文件夹
| | |- index.js //store主文件
| | └─ module //store模块文件夹
| | | └─ user.js //存放user相关的全局变量
| ├─ main.js
接下来,在相应的文件夹中写入以下内容
//index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
user
}
})
//user.js
const state = ({ //state里面存放的是变量,如果你要注册全局变量,写这里
username:'',
});
const getters = { //getters相当于是state的计算属性,如果你需要将变量的值进行计算,然后输出,写这里
fullName(state){
return state.username + '大王';
}}
;
const mutations = { //修改store中的变量的方法,如果你要改变变量的值,就写这里
SET_username(state, value) {
state.username = value;
},
};
const actions = { //actions提交的是mutations,相当于就是改变变量的方法的重写,但是,actions是可以进行异步操作的
setUsername(content) {
content.commit('SET_username');
}
};
export default{
namespaced:true,
state,
getters,
mutations,
actions
};
//main.js
import Vue from 'vue'
import App from './App'
import store from './store/index'
new Vue({
el: '#app',
store,
components: { App },
template: '<App/>'
});
在上面的代码中,已经实现了vuex的模块化,定义State,Getter,Mutation,Action
等所有基本的功能。
页面中的使用
-
直接使用
state => this.$store.state.user.username
getter => this.$store.getters.user.fullName
mutation => this.$store.commit('user/SET_username','cooldream')
此时的username
值为cooldreammutation => this.$store.dispatch('user/SET_username')
action未找到传值的方法
-
使用辅助函数
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
name: "Parent",
computed:{
...mapState({
username:state=>state.user.username //用this.username即可访问
}),
...mapGetters({
fullName:'user/fullName' //用this.fullName可访问
})
},
methods:{
...mapMutations({
setName:'user/SET_username' //this.setName('cooldream'); 即可将值变为cooldream
}),
...mapActions({
asyncSetName:'user/setUsername' //this.asyncSetName(); 即可调用commit('user/setUsername')
})
},
}
</script>
网友评论