Vuex入门,配置
下载 npm install vuex
在src文件夹中创建一个store的文件夹
创建五个js文件
- 在main.js中配置vuex
// 引入vuex
import Vuex from 'vuex'
import store from './store'
Vue.use(Vuex)
new Vue({
el: '#app',
router,
store, // 在main.js中导入store实例
components: { App },
template: '<App/>',
data: {// 在main.js设置
// 自定义的事件总线对象,用于父子组件的通信
Bus: new Vue()
}
})
- 在store中的index文件中配置以下代码
//在index中配置
import Vue from 'vue'
import Vuex from 'vuex'
import state from '@/store/state'
import actions from '@/store/actions'
import mutations from '@/store/mutations'
import getters from '@/store/getters'
Vue.use(Vuex)
const store = new Vuex.Store({
state, // 共同维护的一个状态,state里面可以是很多个全局状态
getters, // 获取数据并渲染
actions, // 数据的异步操作
mutations // 处理数据的唯一途径,state的改变或赋值只能在这里
})
export default store
现在配置已完成,写个dome测试一下
Dome
页面代码
方法
methods: {
/**
* 获取方法
*/
getvuex: function () {
this.date = this.$store.getters.resturantName
},
/**
* 设置方法
*/
setvue: function () {
this.$store.commit('setResturantName', {
resturantName: 'KFC'
})
this.getvuex()
},
/**
* 异步提交方法
* vuex中使用axios提交需要获取this所以这边用_this将this传递过去
* 下面模拟提交的是传递id查询姓名
*/
ajax: function () {
this.$store.dispatch('setResturantNameAsyncAjax', {
_this: this,
userId: 1
})
}
}
定义个变量
data: function () {
return {
date: new Date().getTime(),
}
},
再定义几个按钮加上点击事件
{{date}}
<el-button @click="getvuex()">获取</el-button>
<el-button @click="setvue()">改变</el-button>
<el-button @click="ajax()">提交</el-button>
界面如下
Store代码.
1.在state.js中定义一个变量
export default {
resturantName: '飞歌餐馆',
user:null
}
2.在getters.js中编写获取方法
export default {
resturantName: (state) => {
return state.resturantName
}
}
3.在mutation中设置方法
export default {
// type(事件类型): 其值为setResturantName
// payload:官方给它还取了一个高大上的名字:载荷,其实就是一个保存要传递参数的容器
setResturantName: (state, payload) => {
state.resturantName = payload.resturantName
}
}
4.action中编写异步调用方法,Action提交的是mutation
export default {
setResturantNameByAsync: function (context, payload) {
setTimeout(() => {
context.commit('setResturantName', payload.setResturantName)
}, 100)
}
}
5.在vuex中使用axios提交需要获取this
下面是在action中使用,_this则是传递过来的this
这个方法是传递id查询姓名的一个方法
//axios提交方法
setResturantNameAsyncAjax: function (context, payload) {
setTimeout(() => {
let _this = payload._this
let url = _this.axios.urls.SSMUSER_SELECTUSERBYID
_this.axios.post(url, {
userId: payload.userId
}).then(resp => {
console.log(resp.data.userName)
payload.resturantName = resp.data.userName
// 提交mutations
context.commit('setResturantName', payload)
// 刷新
_this.getvuex()
}).catch(resp => {
console.log(resp)
})
}, 100)
}
测试
现在是刚刚进去,值是页面手动定义的date值
点击获取,调用getvue()方法,
现在获取到了我们state中resturantName的值了:飞哥餐厅
点击改变,调用setvue()方法,
我们将resturantName的值改变为了KFC
然后我们再点击提交,将会传递一个id为1的参数去后台查找延时为100ms
现在resturantName的值为张三
注意,这里提交后我在axios方法中刷新了一下重新获取了resturantName
否则要再次点击获取
本篇文章为本人第一次撰写如有不当之处,感谢指正。欢迎一起交流,学习!
记录学习,记录那些年遇到过的坑