home.vue
<template>
<div class="home">
<h1 @click="handleClick">{{myName}}</h1>
</div>
</template>
<script>
export default {
name: 'Home',
computed:{
myName(){
return this.$store.state.name
}
},
methods:{
handleClick(){
// 第一步 必须派发一个action change为action
this.$store.dispatch('change','vuex store 修改后的数据');
},
},
components: {
}
}
</script>
store / index.js
import {createStore} from 'vuex'
export default createStore({
state: {
name: 'dell',
},
// mutation 里面 只允许写同步的代码 不允许写异步代码
mutations: {
// 第四步,对应mutation被执行
change(state,str) {
// 修改数据
// this.state.name = str;
state.name = str;
},
},
actions: {
// 第二步 store感知你触发了一个叫做change的action,执行action
change(store, str) {
// 第三步,提交一个 commit 触发一个mutation
setTimeout(()=>{
console.log('actions - change')
this.commit('change', str)
},2000)
console.log(store)
console.log(str)
}
},
modules: {}
})