一、在平常的vue项目开发中,我们都会遇到vuex,但是我们不一定必须要用vuex,有时候看到有些人无论干啥都用vuex,看着就很重,我们可以不用它,但是不能不会用它,接下来我就先来个简单的教程,肯定会配上注释的,盘它。
import Vue from 'vue'
import Vuex from 'vuex'
//定义state状态值
const state = {
user:{
name:'',
age:'',
}
}
//定义修改state状态值的方法
const mutations = {
getUserInfo(state,provide){
const {name,age} = provide;
state.name = name;
state.age = age
}
}
// 触发mutations方法,现在暂时不讲
const action = {
}
//最后暴露出去
export default Vuex.store({
namespaced: true,
state,
mutations,
actions
})
//在main.js中引入
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
//我们在页面中可以调用
this.$store.state.user //获取user对象
//触发修改state的方法
this.$store.commit('getUserInfo',{name:'张三',age:18})
上面就是简单的运用vuex了,当然这是非常简陋的,那么下一期我就会讲一些真正在实战开发中用到的,上面这个就当是前菜,了解一下即可了。你get到了么。