Vuex-State、Getter、Mutation、Action

一、state(状态)

const store = new Vuex.Store({
  state: {
    count: 0
  }
})

#使用state在 Vue 组件中获取Vuex 状态

(不常用 & 不能改变数据),想要获取数据使用getters

1、this.$store.state.xxx

export default {
  computed: {
    count() {
      return this.$store.state.count
    }
  }
}

2、辅助函数mapState

import { mapState } from 'vuex'

//1、单独使用
export default {
  computed: mapState(['count'])
}

//2、与局部计算属性混合使用
export default {
  computed: {
    ...mapState({})
  }
}

二、getters

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    //Getter 接受 state 作为其第一个参数
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    },
    //Getter 也可以接受其他 getter 作为第二个参数
    doneTodosCount: (state, getters) => {
      return getters.doneTodos.length
    }
  }
})

# 使用getters在 Vue 组件中获取Vuex 状态

(常用 & 可以操作数据),使用getters获取数据,不要直接使用state

1、this.$store.getters.xxx

export default {
  computed: {
    filterTodos() {
      return this.$store.getters.doneTodos
    }
  }
}

2、辅助函数mapGetters

import { mapGetters } from 'vuex'

export default {
  computed: {
    //1、直接使用,不改方法名(目前使用较多)
    ...mapGetters(['doneTodos','doneTodosCount'])

    //2、修改方法名使用(感觉没必要)
    ...mapGetters({
      newNameDoneTodos: 'doneTodos'
    })
  }
}

三、mutations

const SOME_MUTATION = 'SOME_MUTATION'
const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    //接受 state 作为第一个参数
    increment (state) {
      // 变更状态
      state.count++
    },
    decrement (state, n) {
      state.count -= n
    },
    //使用常量替代 Mutation 事件类型
    [SOME_MUTATION](state) {}
  }
})

# 使用mutations在 Vue 组件中修改Vuex 状态

(必须是同步函数),异步使用actions

1、this.$store.commit('xxx')

methods: {
  increment() {
    this.$store.commit("increment")
  },
  decrement() {
    //第二个参数表示向decrement方法中的参数n传值
    //大多数情况下传参应该是一个对象
    this.$store.commit('decrement', 2)
  }
}

2、辅助函数mapMutations

import { mapMutations } from 'vuex'

export default {
  methods: {
    ...mapMutations(['increment'])
  }
}

四、actions

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    //Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象
    //context.commit、context.getters、context.state等

    increment (context) {
      context.commit('increment')
    },
    incrementAsync ({ commit }) {
      setTimeout(() => {
        commit('increment')
      }, 1000)
    }
  }
})

# 使用actions提交mutation

actions提交的是 mutation,而不是直接变更状态。以包含任意异步操作

1、this.$store.dispatch('xxx')

export default {
  methods: {
    incrementAsync() {
      this.$store.dispatch('incrementAsync')
    }
  }
}

2、辅助函数mapActions

import { mapActions } from 'vuex'

export default {
  methods: {
    ...mapActions(['incrementAsync'])
  }
}

# 等待异步处理结束后再执行下一步
1、this.$store.dispatch('actionA').then(() => { // ... })

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  },
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

2、async / await

actions: {
  async fetchTodos({ commit }) {
    const response = await axios.get("http://jsonplaceholder.typicode.com/todos");
    commit("setTodos", response.data)
  }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 8,036评论 0 7
  • 目录 - 1.什么是vuex? - 2.为什么要使用Vuex? - 3.vuex的核心概念?||如何在组件中去使用...
    我跟你蒋阅读 9,585评论 4 51
  • vuex 场景重现:一个用户在注册页面注册了手机号码,跳转到登录页面也想拿到这个手机号码,你可以通过vue的组件化...
    sunny519111阅读 12,459评论 4 111
  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 8,320评论 0 6
  • ### store 1. Vue 组件中获得 Vuex 状态 ```js //方式一 全局引入单例类 // 创建一...
    芸豆_6a86阅读 3,030评论 0 0

友情链接更多精彩内容