vuex初级:
export default {
// 组件间公共数据部分
state: {},
// 需要改变state中的数据时,要在mutation⾥定义改变的⽅法
mutations: {},
// 当改变state中的数据是异步操作时,在action⾥定义
actions: {}
}
State
数据,存放⼀些公⽤部分的数据
Mutations
数据怎么改变,定义改变state的⼀些⽅法,同步
Actions
异步改变, 如果需要异步改变state,则在这书写
Parent.vue
<template>
<div>
<h1>Parent</h1>
<m-child msg="from Parent msg" @showMsg="showMsg" ref="child" v-bind="$attrs"></m-child>
<h3>{{ msg }}</h3>
<h5>vuex
<span style="color: red">{{ count }}</span>
</h5>
<button @click="add"></button>
</div>
</template>
<script>
import MChild from './Child'
import {mapState} from 'vuex'
export default {
// computed:{
// count(){
// return this.$store.state.count
// }
// },
computed: {
...mapState({
count: 'count',
})//对象展开运算符
},
data() {
return {
msg: ''
}
},
components: {
MChild
},
methods: {
showMsg(val) {
this.msg = val
},
add() {
this.$store.commit()
this.$store.dispatch('delayAdd')
}
},
mounted() {
console.log(this.$children[0].msg)
console.log('ref', this.$refs.child)
}
}
</script>
<style scoped></style>
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
"count": 0
},
mutations:{
add(state){
state.count++
},
decrease(state){
state.count--
}
},
actions:{
delayAdd(context){
setTimeout(()=>{
context.commit('add')
},1000)
}
}
})
文件结构:
vuex高级
vuex中的计算属性—Getters
当你需要依赖vuex⾥的state中的数据,做进⼀步处理时使⽤
state: {
count: 0,
},
// 根据state中的count进⼀步处理,计算双倍值
getters: {
doubleCount (state) {
return state.count * 2
}
},
模块化概念—Modules
当vuex⾥的数据⼗分庞⼤时,可根据存放的数据所属模块进⾏划分
import Vue from 'vue'
import Vuex from 'vuex'
// 第⼀步 引⼊模块
import text from './text'
Vue.use(Vuex)
// 第⼆步 在初始化store时,加载模块
export default new Vuex.Store({
modules: {
text
}
})
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> `moduleA`'s state
store.state.b // -> `moduleB`'s state
Inside a module’s mutations and getters, the first argument received will be the module’s local state.
const moduleA = {
state: () => ({
count: 0
}),
mutations: {
increment (state) {
// `state` is the local module state
state.count++
}
},
getters: {
doubleCount (state) {
return state.count * 2
}
}
}