建项目没有选择 store,自己建一个 store 文件夹
store 文件夹下新建 index.js
import state from './state'
import mutations from './mutations'
export { state, mutations }
store 文件夹下新建 state.js
export default () => ({
counter: 1,
})
store 文件夹下新建 mutations.js
export default {
add(state, data) {
state.counter = data
},
}
store 文件夹下新建 actions.js
export default {
getData(store, data) {
setTimeout(() => {
store.commit('add', data)
}, 2000)
},
}
.vue 文件中使用
<template>
<div>
{{counter}}
</div>
</template>
computed: {
counter () {
return this.$store.state.counter
}
},
methods: {
setStore () {
this.$store.commit("add", 2)
this.$store.dispatch('getData', 3)
}
}