vuex管理工具
主要功能
1、vuex可以实现vue不同组件之间的状态共享(解决不同组件之间的数据共享)
2、可以实现组件里面数据的持久化
vuex的几个核心概念
- State: 定义数据
- Getters:就像计算属性一样,getter的返回值会跟你局它的依赖被缓存起来,且只有当它的依赖值放生改变的时候才会被重新计算。
- Mutations:定义方法
- Actions:action提交的是mutation,而不是直接变更数据状态,action可以包含任意异步操作。
- Miodules:分割模块
1.简单使用方法 main.js
import { createApp } from 'vue'
import App from './App.vue'
import store from './vuex/store'
const app = createApp(App)
app.use(store)
app.mount('#app')
2.封装体 store.js
import { createStore } from 'vuex'
import containerStore from "./ContainerStore";
// Create a new store instance.
const store = createStore({
modules:{
'containerStore':containerStore
},
state () { //定义数据
return {
count: 0,
msg:'你好getters方法!!!!1234'
}
},
mutations: { //定义方法
increment (state) {
setTimeout(()=>{
state.count++
},1000)
},
setCount(state,step){
state.count = state.count + step
}
},
getters:{//计算属性
reverseMsg(state){
return state.msg.substr(0,state.msg.length - 1).concat(state.count)
}
},
actions:{//异步操作 执行 mutations 里面的方法
incCount(context){
context.commit('increment')
}
}
})
export default store
3.使用方法header.vue
<template>
<div>
header
<p>{{count}}</p>
<p>{{reverseMsg}}</p>
<button @click="add">点我</button>
<button @click="addAction">mapActions</button>
<p></p>
<Container></Container>
</div>
</template>
<script>
import Container from "./Container";
import {mapState, mapGetters,mapActions} from 'vuex'
export default {
name: "Header",
components: {Container},
data() {
return {}
},
methods: {
add() {
//执行方法
// this.$store.commit('increment')
//this.$store.commit('setCount', 10)
},
addAction(){
this.$store.dispatch('incCount')
}
},
computed: {
// count(){
// return this.$store.state.count
// }
...mapState([ //映射 state 里面的数据
'count'
]),
//映射 getters里面的方法
...mapGetters([
'reverseMsg'
]),
//映射 actions 异步操作方法
...mapActions([
'incCount'
])
}
}
</script>
<style scoped>
</style>