问题1:路由传参用params或query,若参数过多,会导致400;
问题2:兄弟组件传值;
问题3:不同组件使用同一组数据时,避免向后台重复请求。
一、下载 :npm install vuex --save
二、注册vuex
方案一:vuex的数据少
//main.js
import Vue from vue;
import Vuex from 'vuex';
Vue.use( Vuex );
const store = new Vuex.Store({
//待添加
})
new Vue({
el: '#app',
store,
render: h => h(App)
})
方案二:vuex的数据多(本人推荐这种方式~~~)
//1.创建common/store.js
import Vue from vue;
import Vuex from 'vuex';
Vue.use( Vuex );
export default new Vuex Store({
//核心概念1: State
//就是Vuex中的公共的状态, 我是将state看作是所有组件的data, 用于保存所有组件的公共数据.
state:{
nameList:["范闲","范思哲","范若若","范健"],
ageList:[6,8,4,10,12],
areasList:[]
},
//核心概念2: Getters
//看做是所有组件的computed属性, 也就是计算属性.
//也可以将getter理解为store的计算属性, getters的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
getters:{
countAge:(state)=>{
let resultAgeList= state.ageList.map( age=> {
return age+10;
})
return resultAgeList;
}
},
//核心概念3: Mutations
//mutations:回调函数,用来操作state中的数据,是它的methods,该函数名官方规定叫type, 第一个参数是state, 第二参数是payload, 也就是自定义的参数.
mutations:{
//定义一个方法areaList添加数据
getAreasList (state,payload){
state.areasList=payload;
},
//定义一个方法ageList修改数据
modifyAgeList(state,payload){
state.ageList.map(age=>{
age-=payload;
})
}
},
//核心概念4: Actions
actions:{
modifyAgeListAsync(context,payload){
setTimeout(() => {
context.commit( 'modifyAgeList', payload ); //context提交
}, 5000)}
)
}
//actions 类似于 mutations,但有以下几点不同:
//-actions提交的是mutations而不是直接变更状态;
//-actions中可以包含异步操作, mutations中绝对不允许出现异步;
//-actions中的回调函数的第一个参数是context, 是一个与store实例具有相同属性和方法的对象
})
//2.在main.js注册store
import store from "../common/store.js"
new Vue({
el: '#app',
store,
render: h => h(App)
})
三、在组件中使用store.js中state的数据
mounted(){
//-State:this.$store.state.nameList
console.log(this.$store.state.nameList);
//-Getter:this.$store.getters.countAge
console.log(this.$store.getters.countAge);
//-Mutations:调用这个里面的方法
this.$store.commit("getAreasList", 可以是从后台获取到的数据);
this.$store.commit("modifyAgeList",3);
//注意:调用mutaions中回调函数, 只能使用this.$store.commit(type, payload)
//-Actions:延迟5秒执行mutations中的方法
this.$store.dispatch('modifyAgeListAsync', 5); //分发actions中的modifyAgeListAsync这个异步函数
}
四、核心概念5: Modules
作用:为了避免每个state,mutations,actions,getters中的内容过多,modules可以进行分模块管理,每个模块都有自己的state,mutations,actions,getter。
const moduleA = {
state: { count: 0 },
mutations: {
increment (state) {
// 这里的 `state` 对象是模块的局部状态
state.count++
}
},
getters: {
doubleCount (state) {
return state.count * 2
},
//这里的 `rootState` 对象是Store全局的状态
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
},
actions: {
incrementIfOddOnRootSum ({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
},
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a.count// -> moduleA 的状态
store.state.b // -> moduleB 的状态