目录
Vue3点这里 https://blog.csdn.net/m0_57904695/article/details/123209597
当然了小伙伴首先用一个东西要搞清楚它是嘛用,它怎么用,我会以最为通俗易懂的事例,详解这篇vuex,最重要的是将学会的东西记录下来,咱们忘了学,学了忘,忘了在学,人嘛都会忘,刻记一点,永远不要放弃, 你 不比任何人要差
纸上学来终觉浅,绝知此事要躬行
vuex概念
vuex 是一个状态管理工具,主要解决大中型复杂项目的 数据共享问题,主要包括 state,mutations,actions,getters 和 modules 5 个要 素,主要流程:在页面通过 调用dispatch触发actions执行异步操作,在vue2中,不需要引入useStore,可以直接this.$store.dispatch,vue3最大的特点是按需引入,用到那个api就要引入那个, actions里有默认参数context,在actions通过context.commit(‘给mutations的事件’,‘给mutations的值’)调用mutations,在mutations中的默认参数是state, mutations是唯一修改state的地方
接下来回以:使用vuex-->高阶辅助函数-->高阶模块化-->如何取出模块化的数据及方法,通篇流程下来贯穿vuex,目的熟练掌握vuex
安装持久化插件
第一步安装 cnpm i vuex-persist --save
第二步 引入 本地存储持久化插件 import vuexPersist from "vuex-persist";
plugins: [ //第三步配置全局
new vuexPersist({
storage: window.localStorage,
}).plugin,
],
页面调用actions的方法:
created() {
this.$store.dispatch("methodName");//调用vuex的异步请求actions
},
注释很重要,切记不要一眼万年,仔细看,去理解,哦 是一目十行,静下心,撑住气,记住你是成大事的!加油,
/**
* store/index.js
*
*/
import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
Vue.use(Vuex);
//vuex下的持久化插件 用在vuex里的插件 !!!所以只能在vuex/store/index 引入
import vuexPersist from "vuex-persist"; //第二步 引入 本地存储持久化插件 第一步安装cnpm i vuex-persist --save
export default new Vuex.Store({ //Store仓库的意思
state: { //存数据 状态的意思 status也是状态的意思
list: [],
},
mutations: { //相当于methods 只有mutations才可以修改该state 转变的意思 commit//委托的意思 第一参数state
changeData(state, val) {
// state.list = val
//不直接将参数赋值,如果本地存储有或空,就将本地的赋值给list,否则直接将参数赋值给list
if (JSON.parse(localStorage.getItem('list')) || []) {
state.list = JSON.parse(localStorage.getItem('list')) || []
} else {
state.list = val
}
//以上代码目的打开页面如果本地有数据,就使用本地的,不会一打开就重新将data.JSON的值赋值给list
console.log(state.list);
},
},
actions: { //动作的意思 执行异步操作的 dispatch//派遣的意思 actions第一个参数永远是context
methodName(context) {
axios.get('/data.json').then(res => {
// console.log(res.data.data);
context.commit('changeData', res.data.data)
//页面触发action,action触发mutation,从而修改state中的数据,因为mutation不能写异步代码
})
}
},
modules: { //加载模块的意思 当数据state较多的时候可以分模块管理
},
getters: { //相当于计算属性 获取的人的意思
//在页面使用 {{$store.getters.obj.num0}}
// obj(state) {
// let num0 = state.list.filter(v => v.status == 0).length
// let num1 = state.list.filter(v => v.status == 1).length
// let num2 = state.list.filter(v => v.status == 2).length
// return { num0, num1, num2 }
// }
},
plugins: [ //第三步配置全局
new vuexPersist({
storage: window.localStorage,
}).plugin,
],
});
建议在computed:{ }中使用,如果在data中使用,修改了vuex的数据data不会改变重新渲染,使用computed当依赖值发生改变就会重新渲染
在页面取vuex的数据如下(不使用辅助函数)
/**
* views/home.vue
*/
<template>
<div class="home">
<div>{{ changeText }}</div> //666 ! 成功修改了state的666变成666 !
</div>
</template>
<script>
export default {
data() {
return {
};
},
computed: {
changeText() {
return (this.$store.state.test = "666 !");
},
},
};
</script>
/**
* store/index.js
*/
export default new Vuex.Store({ //Store仓库的意思
state: { //存数据
test: '666'
},
)}
高阶辅助函数,需引入
为什么用辅助函数
0. 引入辅助函数可以简写不写this.$store.state
需要注意的是mapState和mapGetter是映射为计算属性,获取数据
而mapMutations 和mapActions是映射为methods方法里,修改数据的
1. 有4个辅助函数(4大映射)
mapState,mapActions,mapMutations,mapGetters
2. 辅助函数可以把vuex
中的数据和方法映射到vue组件
中。达到简化操作的目的
mapState 是vuex的一个辅助函数 他可以通过循环vuex中的state中的数据将数据一一取出 方法需要在computed计算属性中使用 使用数组 computed:{...mapStore([‘xx’]}
其他三个同理推出...
使用对象可以重命名vuex的数据名字computed:{{自定义名称:xxx数据}}
用辅助函数调用vuex中的方法
/** * views.home.vue * 调用vuex中的方法 */ <template> <div class="home"> <button @click="btn">按钮</button> </div> </template> <script> import { mapMutations } from "vuex"; export default { data() { return {}; }, methods: { ...mapMutations(["addAge"]),//相当于data中的数据可直接用this调用 btn() { this.addAge(); }, }, }; </script> <style lang="scss" scoped></style>
/** * store/index.js */ mutations: { addAge(state) { alert('789456123') } },
用辅助函数 调用vuex中的数据
/** * views.home.vue * 调用vuex中的数据 */ //1 引入 import { mapState } from 'vuex' //2 在compued使用 computed: { ...mapState(['goods']) // [‘goods’]是数据加中括号[] 可以映射vuex数据到当前页面直接使用vuex/state中的goods数据,不需要$store.state.goods },
//vuex state: { //存数据 goods: '666' },
vuex模块化
text.js内容
export default {
namespaced: true,
state: { test: '测试分模快' },
actions: {},
mutations: {},
getters: {}
}
user.js内容
export default {
namespaced: true,
state: { userInfo: '活在风浪' },
actions: {},
mutations: {},
getters: {}
}
1.先新建文件,文件内容写好后,在store/index.js的modules注册
modules: { //加载模块的意思 当数据state较多的时候可以分模块管理
user,
text
},
2.在使用的页面用$store.state.分模块文件名.分模块的数据
<template> <div class="home"> <button @click="btn">按钮</button> <div>{{$store.state.user.userInfo}}</div> </div> </template>
3.建议在使用的页面中的 computed 里定义取vuex分模块数据,data有缓存,修改会拿缓存不会及时渲染,
<template> <div class="home"> <button @click="btn">按钮</button> <div>{{$store.state.user.userInfo}}</div> <div>{{getText}}</div> </div> </template> <script> export default { data() { return {}; }, computed: { getText(){ return (this.$store.state.text.test) } }, }; </script>
4.调用分模块的方法,要在方法前加上分模块的文件名字以斜杠隔开
store/user.js
export default {
namespaced: true, // 如果不使用命名空间, 那么view 指向actions 的该方法时,会执行所有与指定action名相同的函数(即:这里module user,text 中该action都会执行)
state: { userInfo: '活在风浪' },
actions: {},
mutations: {
choseUserInfo(state) {
state.userInfo = '浪风在活'
}
},
getters: {}
}
views/home.vue
<template> <div class="home"> <div>{{$store.state.user.userInfo}}</div> <button @click="choseUserInfo">调用分模块Btn</button> </div> </template> <script> export default { data() { return {}; }, methods: { choseUserInfo(){ this.$store.commit('user/choseUserInfo');//在调用方法前加模块文件名以斜杠分隔 } }, }; </script>
分模块流程图如下
分模块的辅助函数用法
store/text.js文件
export default {
namespaced: true,
state: { test: '测试分模快' },
actions: {},
mutations: {},
getters: {}
}
store/user.js文件
export default {
namespaced: true,
state: { userInfo: '活在风浪' },
actions: {},
mutations: {
choseUserInfo(state) {
state.userInfo = '浪风在活'
}
},
getters: {}
}
在页面使用分模块辅助函数
<template> <div class="home"> <div>{{test}}</div> <div>{{userInfo}}</div> </div> </template> <script> //1.创建辅助物体,目的是取出分模块的辅助函数 import { createNamespacedHelpers } from "vuex"; //2.对象按照key解构,在起个别名,用来区分不同模块的4个辅助函数 const {mapState:mapStateUser,mapActions:mapActionUser,mapMutations:mapMutaionuser} = createNamespacedHelpers('user') const {mapState:mapStateText,mapActions:mapActionText,mapMutations:mapMutaionText} = createNamespacedHelpers('text') export default { data() { return {}; }, computed: { // 3.映射 //映射user.js模块中的state里userInfo这个数据, //可以直接使用不需要在$store.state.user.userInfo ...mapStateUser(['userInfo']), ...mapStateText(['test']) }, }; </script> <style lang="scss" scoped></style>
好了 到此Vue2的vuex基本学完
Vue3的vuex等几天会再次更新出来...
Vue3 https://blog.csdn.net/m0_57904695/article/details/123209597
2022/3/1