目录
一、前言
二、vuex介绍
三、项目搭建
四、vuex使用
①state
②mutations
③actions
一、前言
学习了vue3.0,vuex也是一个必不可少的知识点。在学习完后,也可以发现vuex也是比较容易上手。提示:项目是用vue-cli进行搭建的。
二、vuex介绍
- 官网介绍:Vuex是一个专门为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化
- 我们理解:Vuex是采用集中式管理组件依赖的共享数据的一个工具vue插件,可以解决不同组件数据共享问题
- state管理数据,管理的数据是响应式的,当数据改变时驱动视图更新。=>类似与组件的data
- mutations更新数据,state中的数据只能使用mutations去改变数据
- actions 把数据提交给mutations,可以进行异步操作,不能直接修改state
- getters 对数据获取之前进行再次编译,可以理解为state的计算属性
- modules 它可以来帮我们的状态树分隔成不同的模块,由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
三、项目搭建
首先使用vue-cli创建一个项目
vue create app(项目名称)
创建项目没选择vuex,需要单独安装和初始化
npm i vuex --save
创建store文件,项目文件目录如下
store的index.js
// 准备引入 vuex
import { createStore } from 'vuex'
const store = createStore({
// state:{},
state(){},
mutations:{},
getters:{},
actions:{},
modules:{}
})
export default store
main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
// 引入 vuex
import store from './store/index'
// 引入 animate.css --save 动画插件
import 'animate.css'
// 挂载
createApp(App).use(router).use(store).mount('#app')
四、vuex使用
①state
<script>
import {ref,computed} from 'vue'
import {useStore} from 'vuex'
export default {
setup() {
// 方式一
const msg = ref(null);
const store = useStore();
console.log(store.state);
msg.value = store.state.msg;
// 方式二
const computedMsg= computed(()=> store.state.msg)
return{
msg,
computedMsg
}
},
}
</script>
②mutations
mutations:{
addCount(state){
state.count++
},
reduceCount(state){
state.count--
}
},
在组件调用
methods:{
...mapMutations(['addCount']),
add(){
// this.$storemit('addCount');
// 方式二
this.addCount()
},
reduce(){
this.$storemit('reduceCount');
}
}
③actions
actions:{
asyncAddCount(context){
setTimeout(()=>{
contextmit('addCount')
},1000)
},
asyncReduceCount(context){
setTimeout(()=>{
contextmit('reduceCount')
},1000)
}
},
组件中
<template>
<div class="about">
<h1>about</h1>
count:{{count}}----{{$store.state.count}}
<hr>
<button @click="add">count++</button> <button @click="reduce">count--</button>
<br>
<button @click="asyncAdd">async count++</button> <button @click="asyncReduce">async count--</button>
</div>
</template>
<script>
import {ref,computed,onUpdated} from 'vue'
import {useStore,mapMutations,mapActions} from 'vuex'
export default {
setup() {
// 方式一
const count = ref(null);
const store = useStore();
count.value = store.state.count
onUpdated(()=>{
count.value = store.state.count
})
return{
count
}
},
methods:{
...mapMutations(['addCount']),
...mapActions(['asyncAddCount']),
add(){
// this.$storemit('addCount');
// 方式二
this.addCount()
},
reduce(){
this.$storemit('reduceCount');
},
asyncAdd(){
// this.$store.dispatch('asyncAddCount')
//方式二
this.asyncAddCount()
},
asyncReduce(){
this.$store.dispatch('asyncReduceCount')
}
}
}
</script>
ps:getters和modules下期提到哦!是不是很简单!小伙伴们快试试吧!
更多推荐
vue3.0中使用vuex
发布评论