写给新手同学的vuex快速上手指北小结

2020-06-16 06:56:41易采站长站整理

本文介绍了写给新手同学的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;
}
},
}


<!--mapState 直接取出-->
import { mapState } from 'vuex'
export default {
computed: mapState([
'token',
'name'
])
}

我们有局部计算,怎么和mapState一起用?


import { mapState } from 'vuex'
export default {
computed:{
getTime(){
return 123;
},
...mapState([
'token',
'name'
])
}
}

我们为它起个别名


<template>
<div>
xiaokeai,dahuilang是我们取的别名
token,name是state的值
{{xiaokeai}}
</div>
<template>
<script>
import { mapState } from 'vuex'
export default {
computed:{
...mapState({
xiaokeai:"token",
dahuilang:"name",
})
}
}
</script>

我们要state和data发生点什么