vuex存取值的两种方式
September 18, 2021
3551
一、vuex的执行流程及使用时机
执行流程:组件通过dispatch调用action,action通过commit来触发mutation,mutation来负责修改state,state修改后去重新渲染受影响的dom。
使用时机:vuex 更多地用于解决跨组件通信以及作为数据中心集中式存储数据。
二、安装和引入及挂载
阅读文章:https://blog.csdn.net/qq_32099833/article/details/103000552
三、使用
1、方式一
第一种使用方式:简单 (官方不推荐,但简单)
1
2
3
4从store中获取值:$store.state.a
从getters中获取值:$store.getters.getA
改变vuex的值(同步): $store.commit('add',5)"
改变vuex的值(异步): $store.dispatch('add',5)"
2、方式二
第二种使用方式: 映射函数(官方推荐,但麻烦)
(1)映射关系:
1
2
3
4mapState > computed
mapGetters > computed
mapMutations > methods
mapActions > methods(2)mapState:通过computed来获取,但是如果需要获取多个值就会很麻烦
(3)mapState:通过computed来获取,但是如果需要获取多个值就会很麻烦
(4)mapMutations:同步
(5) mapActions:异步
四、Modules
当系统比较庞大时,store会变得非常臃肿。
为了方便store的模块化管理,Vuex 允许我们将 store 分割成 modules。
每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块。
五、在vue3.0中使用
通过getCurrentInstance指向this
1
2
3
4
5
6
7
8
9
10
11
12<script>
import { getCurrentInstance} from "vue";
export default {
setup(){
//getCurrentInstance代表全局上下文,ctx相当于Vue2的this,
//但是特别注意ctx代替this只适用于开发阶段,等你放到服务器上运行就会出错,
//后来查阅资料说的得用proxy替代ctx,才能在你项目正式上线版本正常运行
let {ctx,proxy}=getCurrentInstance();
proxy.$store.state.a
};
}
</script>
- 本文作者:wowangmouren
- 本文链接:https://wangwewntao.top/2021/09/18/wmr_05/index.html
- 版权声明:本博客所有文章均采用 BY-NC-SA 许可协议,转载请注明出处!