程序员书籍笔记 程序员书籍笔记
  • HTML
  • CSS
  • JavaScript
  • 前端知识
  • Vue
  • MarkDown
  • git
  • Node.js
  • Linux
  • 51单片机
  • 四级
  • 第一学期课程
  • 操作系统
  • 计算机网络
  • 数据结构
  • 计算机组成原理
  • HTML5
  • Electron
  • 日记便签
  • 前端导航
GitHub (opens new window)
  • HTML
  • CSS
  • JavaScript
  • 前端知识
  • Vue
  • MarkDown
  • git
  • Node.js
  • Linux
  • 51单片机
  • 四级
  • 第一学期课程
  • 操作系统
  • 计算机网络
  • 数据结构
  • 计算机组成原理
  • HTML5
  • Electron
  • 日记便签
  • 前端导航
GitHub (opens new window)
  • Vue

    • Vue基础
    • Vue前置知识
    • webpack
    • Vue基本使用
    • Vue基本使用+
    • Vue组件
    • Vue生命周期
    • Vue生命周期+
    • Vue插槽
    • Vue组件库
    • 网易云音乐案例
    • 案例
    • Vuex
      • 基本使用
        • state
        • mutations
        • actions
        • getters
      • vuex模块化
        • 模块化的基本使用
        • 命名空间
      • 案例
        • index.js
        • catagtory.js
        • catagtory.vue
        • newlist.js
        • newlist.vue
    • Vue3.0
    • vue动画
    • 项目常用

    • 问题记录

    • vue模板
  • Nuxt

  • Echarts

  • Node

  • git

  • express

  • 微信小程序

  • Spring

  • 后端知识

  • Markdown

  • project

  • 自用文档查询

  • 框架和软件
  • Vue
yuadh
2022-03-18
目录

Vuex

uex是一个专门为Vue.js` 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种 可预测的方式发送变化

Vuex 采用集中式管理组件依赖的共享数据的一个工具,可以解决不同组件之间数据共享问题

  • state:存储共享状态数据
  • mutaitions :修改 state 里的数据,但是只能修改同步代码,不能修改异步
  • actions:可以修改异步代码 , 将修改的异步代码传给 Mutaitions

# 基本使用

import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
	state:{
		count:0//存储的数据
	}
}) // 实例化对象
//挂载到vue实例
new Vue({
	render:h=>h(app),
	store
}).$mount('#app')
1
2
3
4
5
6
7
8
9
10
11
12

# state

获取方式1 : 原始获取

<div>$store.state.count</div>
1

此获取可以使用计算属性,来简便获取 store 存储的值

computed:{
	count(){
		return this.$store.state.count
	}
}
1
2
3
4
5

获取方式2:辅助函数获取

//导入 mapState
import {mapState} from 'vuex'
//引入state属性
mapState(['count']) 
//延展运算符导出到计算属性
computed:{
	...mapState(['count'])
}
1
2
3
4
5
6
7
8

# mutations

修改方法

const store = new Vuex.Store({
	state:{
		count:0//存储的数据
	},
    mutations:{
        //每一个mutation方法都有对应的参数
        //payload 载荷 提交 mutation的方法 传递的参数 它可以是任意形式的
        addCount(state,payload){
            state.count +=payload
        }
    }
}) // 实例化对象
1
2
3
4
5
6
7
8
9
10
11
12

**修改方法1:**原始修改

methods:{
	test(){
		//第二个参数是要传递的载荷 payload
		this.$store.commit('addCount',1)
	}
}
1
2
3
4
5
6

修改方法2: 辅助函数获取

import {mapMutations} from 'vuex'
methods:{
	...mapMutations(['addCont'])
}
1
2
3
4

# actions

修改方法

const store = new Vuex.Store({
	state:{
		count:0//存储的数据
	},
    mutations:{
        //每一个mutation方法都有对应的参数
        //payload 载荷 提交 mutation的方法 传递的参数 它可以是任意形式的
        addCount(state,payload){
            state.count +=payload
        }
    },
    actions:{
        getAsyncCounf(context,params){
            setTimeout(function(){
                context.commit("addCount",params)
            },1000)
        }
    }
}) // 实例化对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

修改方法1:原始形式

<div @click="getAsyncCount">
    
</div>
test(){
	this.$store.dispatch('getAsyncCont',111)
}
1
2
3
4
5
6

修改方法2:

import {mapActions} from 'vuex'
<div @click="getAsyncCount(111)">
methods:{
	...mapActions(['getAsyncCont'])
}
1
2
3
4
5

# getters

const store = new Vuex.Store({
	state:{
		count:0//存储的数据
		list:[1,2,3,4,5,6,7,8,9]
	},
    /...
}) // 实例化对象
1
2
3
4
5
6
7

定义getters

const store = new Vuex.Store({
	state:{
		count:0//存储的数据
		list:[1,2,3,4,5,6,7,8,9]
	},
	getters:{
		filterList: state=>state.list.filter(item=>imte>5)
	}
    //...
}) // 实例化对象
1
2
3
4
5
6
7
8
9
10

使用方式1:原始使用

<div>
    {{$store.getters.filterList}}
</div>
1
2
3

使用方式2:辅助函数 mapGetters

import {mapGetters} from 'vuex'
computed:{
	...mapGetters(['filterList'])
}
<div>
    {{filterList}}
</div>
1
2
3
4
5
6
7

# vuex模块化

方便管理,避免臃肿

# 模块化的基本使用

const store = new Vuex.Store({
	state:{
		count:0//存储的数据
		list:[1,2,3,4,5,6,7,8,9]
	},
	getters:{
		filterList: state=>state.list.filter(item=>imte>5)
	}
    //...
	modules:{
		//子模块代码
		user:{
			state:{
				token:'123'
			}
		},
		setting:{
			state:{
				token:'Vuex实例'
			}
		}
	}
}) // 实例化对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

使用方式1:

<div>
    {{$store.state.user.token}}
</div>
1
2
3

使用方式2: 使用 getters 属性和辅助函数的方法

const store = new Vuex.Store({
	state:{
		count:0//存储的数据
		list:[1,2,3,4,5,6,7,8,9]
	},
	getters:{
		filterList: state=>state.list.filter(item=>imte>5)
		token:state=>state.user.token,
		name: state=>state.setting.name
	}
    //...
	modules:{
		//子模块代码
		user:{
			state:{
				token:'123'
			}
		},
		setting:{
			state:{
				name:'Vuex实例'
			}
		}
	}
}) // 实例化对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

使用

import {mapGetters} form 'vuex'
computed:{
	...mapGetters(['token','name'])
}
1
2
3
4

# 命名空间

默认情况下,模块内部的 action mutaton getter 模块是注册在全局命名空间的

这样使得多个模块能够对同一个 mutation 或 action 做出响应

如果想保证子模块内部的封闭性,可以通过命名空间 namespaced 设置

const store = new Vuex.Store({
    //...
	modules:{
		//子模块代码
		user:{
            namespaced:true,
			state:{
				token:'123'
			},
			mutations:{
				updataToken(state){
					state.token = '111'
				}
			}
		},
		setting:{
			state:{
				name:'Vuex实例'
			}
		}
	}
}) // 实例化对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

通过命名空间的子模块不能直接被调用,如果要调用需要加上路径名

this.$store.commit('user/UpdateToken')
1

使用方法1 :普通使用

const store = new Vuex.Store({
    //...
	modules:{
		//子模块代码
		user:{
			state:{
				token:'123'
			},
			mutations:{
				updataToken(state){
					state.token = '111'
				}
			}
		},
		setting:{
			state:{
				name:'Vuex实例'
			}
		}
	}
}) // 实例化对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

使用

<div>
    
</div>

methods:{
	updateToken(){
		this.$store.commit('updateToken')
	}
}
1
2
3
4
5
6
7
8
9

使用方式2: 辅助函数

mapMutations

使用了命名空间的模块,直接使用辅助函数可能会报错

使用

methods:{
	...mapMutations(['user/updateToken'])
	test(){
 		this['user/updateToken']()       
    }
}
1
2
3
4
5
6

使用方式3: 命名空间辅助函数

import {createNamespaceHelpers} from 'vuex'
const {mapMutations} = createNamespaceHelpers('user')//子模块
methods:{
    ...mapMutations(['updateToken'])
}
1
2
3
4
5

# 案例

基地址:http://toutiao.itheima.net

对头条案例,使用 vuex 进行封装

案例中 vuex 的使用写成独立的模块

store/index.js

# index.js

import Vuex from 'vuex'
import Vue from 'vue'
import categtory from './modules/catagtory'
import newlist from './modules/newlist'
Vue.use(Vuex)
export default new Vuex.Store({
    state:{
        
    },
    mutations:{
        
    },
    actons:{
        
    },
    modules:{
        catagroy,
        newlist
    },
    getters:{
        catagtory:state=>state.catagtory.catagtory,
        currentCatagtory:state=>state.catagtory.currentCatagtory
    	currentList:state=>state.newlist.allData[state.catagtory.currentCatagtory]||[]
    }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# catagtory.js

export default{
    namespaced:true,
    state:{
        catagtory:[],
        currentCatagtory:''
    },
    mutations:{
        updateCatagtory(state,payload){
            state.catagtory = payload
        },
        updateCurrentCatagtory(state,payload){
            state.crrentCatatory = payload
        }
    },
    actions:{
        async getCatagtory(context){
        	const {data:{data:{channels}}= await axios.get('urlAPI')
        	context.commit('updataCatagtory',channels)
            context.commit('updataCurrentCatagtory',channels[0].id)
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# catagtory.vue

catagtory.vue

<ul class="catagtory">
	<li 
	@click='$store.commit("catagtory/updateCurrentCatagtory",item.id)'
	:class="{select:item.id===currentCatagtory}"
	v-for= "item in catagtory" :key="item.id"
</ul>

//...调用
computed:{
	...mapGetters(['catatory','currentCatagtory'])
},
created(){
	//vue实例创建之后请求获取到数据
	this.$store.dispatch('catagtory/getCatagtory')
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# newlist.js

export default{
    namespaced:true,
    state:{
       allData:{}
    },
    mutations:{
        updataList(state,{currentCatagtory,list}){
        //因为组件需要变动才会被通知,所以仅是值的变化无法通知组件也就刷新不来数据
			state.allData = {...state.allData,[currentCatagtory]:list}
        }
    },
    actions:{
        async getNewList(context,cataId){
        	const {data:{data:{results}}} = await axios.get('urlapi')
            context.commit('updataList',{currentCatagtory:cataId
                                        ,list:results})
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# newlist.vue

<template>
	currentList.id...
</template>

watch:{
	computed:{
		...mapGetters(['currentCatagtory','currentList'])
	},
	watch:{
		currentCatagtory(newValue){
			this.$store.dispatch('newlist/getNewList',newvalue)
		}
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
编辑 (opens new window)
上次更新: 2023/02/07, 14:51:48
案例
Vue3.0

← 案例 Vue3.0→

Theme by Vdoing | Copyright © 2021-2023 yuadh
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×