Foreword:
Here to share the usage of vuex in personal projects. Vuex is mainly used to directly pass values between different levels of components.
Analysis logic:
Page a and page b have different logic, a page click event, b page needs to be able to monitor
Introduction of vuex: divided into 4 states
1、state 这里跟我们页面上的data很类似是定义变量的
2、mutations vuex的逻辑操作修改都在这个阶段里面进行
3、actions vuex里面 如果想请求后台的话,必须在这个阶段里面进行
4、getters 在这个阶段,可以把state里面的值发送出去,页面也需要监听这个阶段的值
因为我们的vuex可能分为很多模块,这里就需要用到他的 modules
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user' //其中一个模块
import getters from './getters'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
user, //注册在这里
},
getters
})
export default store
Personal use steps:
One defines what is needed in vuex
First create a store folder like this, the content in the user.js file is like this
const user = {
state: {
menuClick: {},//当前点击的情况
sbzqClick:{},
},
mutations: {
//修改state里面的menuClick
SET_MENU_CLCIK: (state, data) => {
state.menuClick = data
},
SET_SBZQ_CLCIK: (state, data) => {
state.sbzqClick = data
},
},
actions: {
}
}
export default user
The content in getters.js is like this
const getters = {
menuClick: state => state.user.menuClick,
sbzqClick:state => state.user.sbzqClick,
}
export default getters
The content in index.js is like this
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import getters from './getters'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
user, },
getters
})
export default store
Second, solve the actual click cross-component transfer
Now we have a problem like this
Click the menu bar on the left, and want to change the value in the drop-down list of reporting period on the right? ? ? ? How to do it The idea is this:
1. First, we write the sending event on the method of the click event of the a component . Look at the picture to explain this part of the specific status sent by the menu bar on the right ;
Next is the specific operation in our vuex, look at the picture
Then we receive and use him in the b component , the first step is to introduce: (this sentence must be introduced)
import { mapGetters, mapActions } from 'vuex'
The second step:
The code bia comes up for the next operation
computed: {
...mapGetters(['menuClick'])
},
watch: {
...mapGetters(['menuClick']),
/**
* 用vuex实时监听state里面menuClick的变换
* */
menuClick(val){
let djxh = val.djxh
this.sbzjxVal = '';//默认
this.getYear(djxh);
}
},