写给新手同学的写给新手同学的vuex快速上手指北小结快速上手指北小结
本文介绍了写给新手同学的vuex快速上手指北小结,分享给大家,具体如下
引入引入
//store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {...},
mutations: {...},
actions: {...}
})
export default store
//main.js
...
import store from './store'
Vue.prototype.$store = store
const app = new Vue({
store,...
})
...
//test.vue 使用时:
import {mapState,mapMutations} from 'vuex'
State篇篇
state更新实时渲染是基于==computed==这个计算属性的,直接赋给data只能赋值初始值,不会随着state改变实时渲染
<!--state改变不会实时渲染-->
export default {
data() {
return {
name:this.$store.state.name,
};
},
}
<!--监听state改变重新渲染视图-->
<template>
<div>
{{name}}
</div>
<template>
export default {
computed: {
name() {
return this.$store.state.name;
}
},
}
注意: data中的变量如果和computed中的变量重名,data优先,注意命名
获取多个state值,写多个函数return,很繁琐,所以有==mapState==辅助函数
<!--取多个很冗余,繁琐-->
export default {
computed: {
token(){
return this.$store.state.token;
},
name(){
return this.$store.state.name;
}
},
}