vuex.png

  1. export default new Vuex.Store({
  2. state: {
  3. city:"武汉"
  4. },
  5. //简单的状态逻辑写在mutations中
  6. mutations: {
  7. //可以更改状态
  8. },
  9. //复杂的业务逻辑写在actions中,异步操作方法这里
  10. actions: {
  11. //异步提交更改
  12. }
  13. })
  1. //main.js
  2. new Vue({
  3. store // 会在所有的组件上挂载一个$store属性
  4. })

一 正常的工作流

  1. <template>
  2. <div>
  3. <button @click="changeCity(item)" v-for="(item,index) of citys" :key="index">{{item}}</button>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. data(){
  9. return {
  10. citys:["武汉","杭州","厦门"]
  11. }
  12. },
  13. methods:{
  14. changeCity(city){
  15. console.log(city)
  16. // console.log(this)
  17. this.$store.dispatch("changeCity",city);
  18. }
  19. }
  20. };
  21. </script>
//vuex
export default new Vuex.Store({
  state: {
    city:"武汉"
  },
  mutations: {
    changeStateCity(state,val){
      console.log(val)
      state.city = val
    }
  },
  actions: {
    changeCity(ctx,val){
      ctx.commit("changeStateCity",val)
    }
  },
  modules: {
  }
})