一、vuex安装以及使用

vue引入vuex以及封装axios - 图1

安装vuex

  1. npm install vuex@next --save

简单例子

  1. import { createStore } from 'vuex';
  2. // https://www.it610.com/article/1282865199115681792.htm
  3. const store = createStore({
  4. state () {
  5. return {
  6. count: 0,
  7. index: 0
  8. }
  9. },
  10. // mutations state成员操作 实际修改状态值的
  11. mutations: {
  12. //定义方法,在组件内使用:this.$store.commit("updata",参数)
  13. updata(state, num) {
  14. // 获取 state.变量 得到state里面的数据,num 接收参数变量
  15. state.index = num;
  16. },
  17. increment (state) {
  18. state.count++
  19. }
  20. },
  21. // actions 异步操作 用来处理异步的
  22. // Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,
  23. //因此你可以调用 context.commit 提交一个 mutation,或者通过
  24. // context.state 和 context.getters 来获取 state 和 getters。
  25. // 组件内使用: this.$store.dispatch("nameAsyn") 调用
  26. actions: {
  27. nameAsyn(context) {
  28. setTimeout(() => {
  29. context.commit('updata', 8);
  30. }, 1000);
  31. }
  32. },
  33. // modules 模块化状态管理
  34. modules: {
  35. },
  36. //Getters可以对state中的成员加工后传递给外界,Getters中的方法有两个默认参数
  37. //state 当前VueX对象中的状态对象
  38. //getters 当前getters对象,用于将getters下的其他getter拿来用
  39. //了解
  40. getters: {
  41. //组件内使用:this.$store.getters.personInfo 得到返回值 + 1
  42. personInfo(state) {
  43. return state.index + 1;
  44. },
  45. //函数 getData:(state) => (id) => {...}
  46. //使用:this.$store.getters.getData(2)
  47. getData: (state) => (id) => {
  48. return state.num + id
  49. }
  50. }
  51. });
  52. export default store;

二、axios安装以及封装使用
1、安装 axios

  1. npm install axios --save