vue3
import { createStore } from 'vuex'
export default createStore({
state: {
username: 'zs',
age: 56
},
getters: {
newName (state) {
return state.username + '!!!'
},
},
mutations: {
updateName (state) {
state.username = 'ls'
},
updateAge (state, playLoad) {
console.log("playLoad", playLoad)
state.age += playLoad
}
},
actions: {
updateName (ctx) {
console.log('触发了')
setTimeout(() => {
ctx.commit('updateAge', 46)
}, 1000)
}
},
modules: {
}
})
App.vue
<template>
<!-- vue2.0需要根元素,vue3.0可以是代码片段 fragment -->
<div>
App
<!-- 1、使用根模块state的数据 -->
<h1>{{ $store.state.username }}</h1>
<!-- 2、使用根模块getters的数据 -->
<h1>{{ $store.getters.newName }}</h1>
<h1>{{ $store.getters["newName"] }}</h1>
<button @click="mutationsFn">按钮</button>
<h1>{{ $store.state.age }}</h1>
<button @click="actionsFn">改变年龄</button>
</div>
<p>p</p>
</template>
<script>
import { useStore } from "vuex";
export default {
name: "App",
setup () {
const store = useStore();
console.log(store);
console.log(store.state.username);
console.log(store.getters.newName);
const mutationsFn = () => {
store.commit("updateName");
};
const actionsFn = () => {
store.dispatch('updateName')
}
return {
mutationsFn,
actionsFn
}
},
};
</script>
<style lang="less">
</style>
|