版本
"core-js": "^3.6.5",
"vue": "^3.0.0",
"vue-router": "^4.0.0-0",
"vuex": "^4.0.0-0"
store/index.js
import { createStore } from 'vuex'
export default createStore({
state: { name: 'dell' },
mutations: {
changeName(state, str) {
state.name = str;
}
},
actions: {
getData(store) {
setTimeout(() => {
store.commit('changeName', 'hello')
}, 2000)
}
}
})
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png">
<h1>{{name}}</h1>
</div>
</template>
<script>
import { toRefs } from 'vue';
import { useStore } from 'vuex';
export default {
name: 'Home',
setup() {
const store = useStore();
const { name } = toRefs(store.state);
return { name }
}
}
</script>
<template>
<div class="about">
<h1 @click="handleClick">This is an about page</h1>
<h1>{{name}}</h1>
</div>
</template>
<script>
import { toRefs } from 'vue';
import { useStore } from 'vuex';
export default {
name: 'Home',
setup() {
const store = useStore();
const { name } = toRefs(store.state);
const handleClick = () => {
store.dispatch('getData')
}
return { name, handleClick }
}
}
</script>·