Vue3中使用vuex4的实现示例
1、引入依赖:
npm i vuex
2、新建文件夹 store ,在里面新建文件 index.js

3、index.js文件内容:
import { createStore } from 'vuex'
export default createStore({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})4、在 main.js 中引入
import store from './store'

5、使用
在 store/index.js 的 state 中添加 count: 0

在任一组件文件中:加入下面代码:
import { useStore } from "vuex";
export default {
name: "App",
setup() {
// Vue3 有个 composition api 的入口
const store = useStore();// 获取容器
},
};
获取到容器 store 后 ,获取 Vuex 中的 count 的值,通过 store.state.count 来获取。


直接在 template 中使用,目前可以使用旧版本写法

如果想要字段 count 改变后,页面显示数据也改变,需要引入 vue 的计算属性 computed
<template>
<img alt="Vue logo" src="./assets/logo.png" />
<h1>Vuex</h1>
<h1>{{ count }}</h1>
</template>
<script>
import { computed } from "vue";
import { useStore } from "vuex";
export default {
name: "App",
setup() {
// Vue3 有个 composition api 的入口
const store = useStore(); // 获取容器
// 获取 Vuex 中的 count 的值
console.log("store.state.count", store.state.count);
return {
count: computed(() => store.state.count),
};
},
};
</script>
6、修改 count 的值
这个和在 vue2 中的写法一样
在 store/index.js 中添加下面代码:
mutations: {
add(state, payload) {
state.count += payload
}
},在 要修改 count 的值的组件中通过 commit 来修改
store.commit('add', 3)
到此这篇关于Vue3中使用vuex4的实现示例的文章就介绍到这了,更多相关Vue3使用vuex4内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Vue项目中对index.html中BASE_URL的配置方式
这篇文章主要介绍了Vue项目中对index.html中BASE_URL的配置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-06-06
vue中使用echarts刷新可以正常渲染但路由跳转不显示的问题解决
在 Vue 中使用 ECharts 组件时,遇到路由跳转后图表不显示的问题可能是因为组件销毁和重新创建的原因,所以本文给大家介绍了vue中使用echarts刷新可以正常渲染但路由跳转不显示问题的解决方法,需要的朋友可以参考下2024-02-02


最新评论