-
同vue2 一致
-
使用需要安装,引入
npm install vuex@next --save
store文件中创建index.js
import { createStore } from "vuex";
export default createStore({
//创建仓库
state: {
name: "马云",
},
//--------使用以下方法调用数据仓库里的数据----------
//同步调用
mutations: {
muta(state, poalay) {
state.name = poalay;
},
},
//异步调用
actions: {
act(state) {
state.commit("muta");
},
},
});
在main.js中引入
import createStore from "./store/index";
createApp(App).use(createStore).mount("#app");
在页面中拿到仓库的值和修改vuex中的数据
<template>
<div>
<h1>111 {{ res }}</h1>
<button @click="btn">修改vuex中的数据</button>
</div>
</template>
<script>
import { computed } from "vue";
import { useStore } from "vuex";
export default {
setup() {
//从数据仓库拿到数据
const store = useStore();
const res = computed(() => {
return store.state.name;
});
const btn = () => {
//异步调用:dispatch
// store.dispatch("act");
//同步调用:commit
store.commit("muta", "马化腾");
};
return { res, btn };
},
};
</script>
<style scoped lang="scss"></style>