什么是vuex?
官方的解释是Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
人话:就是一个数据库,我们在学习vue过程中数据传递只能在通过prop和自定义函数在父子组件中传递,但是通过状态管理库我们可以在任意两个组件之间进行数据传递
vuex的安装流程
第一步:安装vuex
npm install vuex@next --save
第二步:创建一个sotre的文件夹并且在里面新建一个index.js,编写如下
import {createStore} from "vuex"
export default createStore({
state:{
conter:0
}
})
第三步:在main.js修改如下
import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
import store from '../store'
createApp(App).use(store).mount('#app')
第四步:在app.vue中引入数据
<template>
<p>counter={{ $store.state.counter }}</p>
<p>couner={{ couner }}</p>
</template>
<script>
import {mapState} from 'vuex'
export default {
computed:{
...mapState(["couner"])
}
}
</script>
这里写了两种引入方式,最后都能在页面显示counter=0
vuex状态管理核心(主要使用方法):state,getter,mutation,action
getter:对vuex中的数据进行过滤
mutation:修改vuex中的数据
action:类似于mutation,但是为了异步操作准备的,mutation只能在同步操作中进行(这里不进行样例展示)
对store的index.js修改如下
import {createStore} from 'vuex'
export default createStore({
state:{
counter:0
},
getters:{
getcounter(state){
return state.counter>0?state.counter:"数据异常"
}
},
mutations:{
addcounter(state,num){
state.counter+=num;
}
}
})
对app.vue修改如下
<template>
<p>counter={{ $store.getters.getcounter }}</p>
<p>counter={{ getcounter }}</p>
<button @click="addClickHandle"></button>
</template>
<script>
import {mapState,mapGetters,mapMutations} from 'vuex'
export default {
computed:{
...mapState(["couner"]),
...mapGetters(["getcounter"])
},
methods:{
...mapMutations(["addcounter"]),
addClickHandle(){
// this.$store.commit("addcounter",15)
this.addcounter(15)
}
}
}
</script>