vuex的简单使用
2019-03-08 本文已影响58人
程序猿阿峰
Vuex是什么?
vuex官网的解释:Vuex
是一个专为Vue.js
应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方法方法变化。
简单的介绍下使用方法
1.首先要安装、使用 vuex
npm install vuex --save
然后在src
文件目录下新建一个名为store
的文件夹,方便引入并在store
文件夹里新建一个index.js
,里面的内容如下:
image.png
// 引用vue
import Vue from 'vue'
// 引用vuex
import Vuex from 'vuex'
// 使用vuex
Vue.use(Vuex)
// new 一个vuex
const store = new Vuex.Store()
// 暴露出去
export default store
接下来,在main.js
里面引入store
,然后再全局注入,这样就可以在任何一个组件中使用this.$store
了,具体如下
// 如果在main.js中,不import vuex -- 后面会报 'dispatch' of undefined 的错误
import Vuex from 'vuex'
// 引入store.js
import store from './store/store.js'
// 使用Vuex
Vue.use(Vuex)
/* eslint-disable no-new */
new Vue({
el: '#app',
store, // 使用store
router,
components: {
App
},
template: '<App/>'
})
2.设计store
通常设计store
对象都包含4个属性:state
getters
actions
mutations
-
state
(类似存储全局变量的数据) → state官方解说视频 -
getters
(提供用来获取state
数据的方法) → getters官方解说视频 -
actions
(提供跟后台接口打交道的方法,并调用mutations
提供的方法) → actions官方解说视频 -
mutations
(提供存储设置state
数据的方法 → mutations官方解说视频
且看官方的一个示例图:
image.png
几个属性之间的关系
- 组件
Vue Compinent
通过dispatch
来调用actions
提供的方法 - 而
actions
除了可以和api
打交道外,还可以通过commit
来调用mutations
提供的方法 - 最后
mutations
将数据保存到state
中 - 当然,
Vue Component
还可以通过getters
提供的方法获取state
中的数据
3.store.js代码
import Vue from 'Vue'
import Vuex from 'vuex'
Vue.use(Vuex)
/**
* 想要操作的数据
*/
const state = { // 设置要全局访问的state对象
toWithdrawFromPath: '' // 跳转到提现页面的路径
}
/**
* 可以用来获取 state 中的数据
*/
const getters = {
/**
* 方法名随意,主要是来承载变化的toWithdrawFromPath的值
* @param {*} state state对象
*/
isHasFromPath (state) {
return state.toWithdrawFromPath
}
}
/**
* 操作states中数据的函数
*/
const mutations = {
/**
* 设置跳转到提现页面的路径
* @param {*} state store对象
* @param {*} value 传过来的值
*/
gettingFromPath (state, value) {
state.toWithdrawFromPath = value
}
}
/**
* 存储着触发 mutations 里面的函数的行为
*/
const actions = {
/**
* 操作设置跳转到提现页面的路径的方法
* @param {*} store store对象
* @param {*} value 传过来的值
*/
settigFromPath (store, value) {
store.commit('gettingFromPath', value)
}
}
/**
* vuex的注册使用
*/
const store = new Vuex.Store({
state,
getters,
mutations,
actions
})
export default store
4.如何在组件中使用
组件页面中的this.$store.dispatch
来调用store.js
中actions
所提供的gettingFromPath
,保存数据
export default {
data () {
return {
}
},
mounted () {
// 通过vuex的getters方法来获取
this.$store.dispatch('settigFromPath', window.location.hash.split('/')[1])
}
}
通过this.$store.getters
来获取store.js
所写getters
提供的settigFromPath
方法
export default {
data () {
return {
}
},
mounted () {
// 通过vuex的getters方法来获取
this.$store.getters.isHasFromPath
}
}
vuex的简单使用,记载下,方便自己以后重新回顾。