目录1、引入依赖:2、新建文件夹 store ,在里面新建文件 index.js3、index.js文件内容:4、在 main.js 中引入5、使用6、修改 count 的值1、引入
npm i Vuex
import { createStore } from 'vuex'
export default createStore({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})
import store from './store'
在 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>
这个和在 vue2 中的写法一样
在 store/index.js 中添加下面代码:
mutations: {
add(state, payload) {
state.count += payload
}
},
在 要修改 count 的值的组件中通过 commit 来修改
store.commit('add', 3)
到此这篇关于Vue3中使用vuex4的实现示例的文章就介绍到这了,更多相关Vue3使用vuex4内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Vue3中使用vuex4的实现示例
本文链接: https://www.lsjlt.com/news/152239.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0