Vuex的组成

Vuex

store实例的创建

const store = new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  getters: {},
  modules: {}
})


const app = new Vue({
  store
})

// 在各个组件中我们都可以获取到this.$store
/* 
  有了this.$store,我们就可以
    获取state this.$store.state.xxx
    获取state this.$store.getters.xxx

    提交mutation this.$store.commit('mutation', 要传递的数据)
    分发action this.$store.dispatch('action', 要传递的数据)

*/

vuex由 state、mutations、actions、getters、modules 组成

state

state用于存储网页中对应组件的所有的数据

const store = new Vuex.Store({
  state: {
    msg: '数据'
  }
})

如果想要组件中使用,可以使用以下方法

const com = {
  computed: {
    msg () {
      return this.$store.state.msg
    }
  }
}

getter

getter的作用,用于从state中动态获取相关数据

const store = new Vuex.Store({
  state: {
    arr: [1,2,3,4]
  },
  getters: {
    arrLength (state, getters) {
      return state.arr.length
    },

    demo (state, getters) {
      return (num) => {
        return num
      }
    }
  }
})

如果要使用getter

const com = {
  computed: {
    arrLength () {
      return this.$store.getters.arrLength
    },
    demo () {
      return this.$store.getters.demo
    }
  }
}
/* 
  使用arrLength时可以直接
  {{arrLength}}
  {{demo(23)}}
*/

mutation

mutation是唯一能够修改state的操作。我们如果想要改变state,就直接的去创建一个mutation,然后提交(commit)这个mutation即可。一般我们会在action进行commit操作

const store = new Vuex.Store({
  state: {
    msg: '默认数据'
  },
  mutations: {
    changeMsg (state, payload) {
      state.msg = payload.msg
    }
  }
})

如果要使用对应的mutation

this.$store.commit('changeMsg', {
  msg: '新的内容'
})

action

我们可以在action中请求接口,获取对原始数据进行处理。action就是为了得到数据的,得到数据后,需要将数据处理并提交给mutation,让mutation对数据进行处理

const store = new Vuex.Store({
  state: {
    msg: '数据'
  },
  mutations: {
    setMsg (state, msg) {
      state.msg = msg
    }
  },
  actions: {
    // context就是个store
    getMsg ({commit}, payload) {
      axios.get(url, data).then(res => {
        // 假设res.data就是我们的新的msg
        commit('setMsg', res.data)
      })
    }
  }
})

如果我们要使用action


this.$store.dispatch('getMsg', 参数)

因为action是异步的,所以我们可以通过下面的方式来获取到异步的结果

// 将action中异步请求renturn即可
{
  actions: {
    getMsg ({commit}, payload) {
      return axios.get(url, data).then(res => {
        // 假设res.data就是我们的新的msg
        commit('setMsg', res.data)
      })
    }
  }
}

this.loading = true
this.$store.dispatch('getMsg', 参数).then(() => {
  // action中的请求结束后执行的函数
  this.loading = false
})

vuex的数据经历了一个循环

组件中想要获取数据 --dispatch–> action --commit–> mutation --mutate–> state --render–> 组件上

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

本地是好的

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值