import {
createStore
} from 'vuex'
export default createStore({
state: {
name: "愣头青",
age: 18,
},
getters: {
changeAge(state) {
return state.age + '岁'
}
},
mutations: {
changeName(state, value) {
state.name = value
},
changeProducts(state, value = []) {
state.products = value
}
},
actions: {
getProducts({
commit
}) {
setTimeout(() => {
commit('changeProducts', [{
name: '这是一个商品'
}])
}, 1000)
}
},
modules: {},
plugins: []
})
vue中
<template>
<div class="home">
{{name}} - {{age}}
<button @click="changeName('杜甫')">修改名字</button>
<button @click="getProducts">点击获取商品数据</button>
<ul>
<li v-for="(item, i) in products" :key="i">{{item.name}}</li>
</ul>
</div>
</template>
<script>
import { defineComponent, computed } from 'vue'
import { useStore } from 'vuex';
export default defineComponent({
setup() {
let store = useStore()
return {
name: computed(() => store.state.name),
age: computed(() => store.getters.changeAge),
changeName: (name) => store.commit('changeName', name),
getProducts: () => store.dispatch('getProducts'),
products: computed(() => store.state.products)
}
}
})
</script>