Vuex 是什么
概念:专门在Vue中实现集中式状态(数据)管理的一个Vue插件,对Vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。
什么时候使用 Vuex:
原理:

使用vuex:
npm i vuex;import Vue from 'vue'
import Vuex from 'vuex' // 引入Vuex
Vue.use(Vuex) // 应用Vuex插件
const actions = {} // 准备actions——用于响应组件中的动作
const mutations = {} // 准备mutations——用于操作数据(state)
const state = {} // 准备state——用于存储数据
// 创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state,
})
import Vue from 'vue'
import App from './App.vue'
import store from './store' // 引入store
Vue.config.productionTip = false
new Vue({
el: '#app',
render: h => h(App),
store, // 配置项添加store
beforeCreate() {
Vue.prototype.$bus = this
}
})
$store.state.数据$store.dispatch('action中的方法名',数据) 或$store.commit('mutations中的方法名',数据) import Vue from 'vue'
import Vuex from 'vuex' // 引入Vuex
Vue.use(Vuex) // 应用Vuex插件
// 准备actions——用于响应组件中的动作
const actions = {
/* jia(context,value){
console.log('actions中的jia被调用了')
context.commit('JIA',value)
},
jian(context,value){
console.log('actions中的jian被调用了')
context.commit('JIAN',value)
}, */
jiaOdd(context,value){ // context 相当于精简版的 $store
console.log('actions中的jiaOdd被调用了')
if(context.state.sum % 2){
context.commit('JIA',value)
}
},
jiaWait(context,value){
console.log('actions中的jiaWait被调用了')
setTimeout(()=>{
context.commit('JIA',value)
},500)
}
}
// 准备mutations——用于操作数据(state)
const mutations = {
JIA(state,value){
console.log('mutations中的JIA被调用了')
state.sum += value
},
JIAN(state,value){
console.log('mutations中的JIAN被调用了')
state.sum -= value
}
}
// 准备state——用于存储数据
const state = {
sum:0 //当前的和
}
// 创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state,
})
使用:
$store.state.sum
getters配置项:
概念:当state中的数据需要经过加工后再使用时,可以使用getters加工,相当于全局计算属性
在store.js中追加getters配置:
const getters = {
bigSum(state){
return state.sum * 10
}
}
// 创建并暴露store
export default new Vuex.Store({
......
getters
})
mapState方法:用于帮助映射state中的数据为计算属性,相当于完成一个等于
computed: {
// 借助mapState生成计算属性:sum、school、subject(对象写法一)
...mapState({sum:'sum',school:'school',subject:'subject'}),
// 借助mapState生成计算属性:sum、school、subject(数组写法二)
...mapState(['sum','school','subject']),
},
mapGetters方法:用于帮助映射getters中的数据为计算属性
computed: {
//借助mapGetters生成计算属性:bigSum(对象写法一)
...mapGetters({bigSum:'bigSum'}),
//借助mapGetters生成计算属性:bigSum(数组写法二)
...mapGetters(['bigSum'])
},
mapActions方法:用于帮助生成与actions对话的方法,即包含$store.dispatch(xxx)的函数
methods:{
//靠mapActions生成:incrementOdd、incrementWait(对象形式)
...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
//靠mapActions生成:incrementOdd、incrementWait(数组形式)
...mapActions(['jiaOdd','jiaWait'])
}
mapMutations方法:用于帮助生成与mutations对话的方法,即包含$store.commit(xxx)的函数
methods:{
//靠mapActions生成:increment、decrement(对象形式)
...mapMutations({increment:'JIA',decrement:'JIAN'}),
//靠mapMutations生成:JIA、JIAN(对象形式)
...mapMutations(['JIA','JIAN']),
}
mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象
组件:
<template>
<div>
<h1>当前求和为:{{ sum }}</h1>
<h3>当前求和的10倍为:{{ bigSum }}</h3>
<h3>我是{{ name }},我在{{ school }}学习</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment(n)">+</button>
<button @click="decrement(n)">-</button>
<button @click="addOdd(n)">当前求和为奇数再加</button>
<button @click="addWait(n)">等一等再加</button>
</div>
</template>
<script>
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex' //🔴
export default {
name: 'Count',
data() {
return {
n:1, //用户选择的数字
}
},
computed: {
...mapState(['sum','school','name']),
...mapGetters(['bigSum'])
},
methods: {
...mapMutations({increment:'ADD', decrement:'SUBTRACT'}),
...mapActions(['addOdd', 'addWait'])
},
}
</script>
<style>
button{
margin-left: 5px;
}
</style>
目的:让代码更好维护,让多种数据分类更加明确
修改store.js
为了解决不同模块命名冲突的问题,将不同模块的namespaced: true,之后在不同页面中引入getteractionsmutations时,需要加上所属的模块名
const countAbout = {
namespaced: true, // 开启命名空间
state: {x:1},
mutations: { ... },
actions: { ... },
getters: {
bigSum(state){ return state.sum * 10 }
}
}
单页Web应用(single page web application,SPA):
路由:一组key-value的对应关系;key为路径,value可能是function或component。
多个路由需要经过路由器的管理。
路由分类:
import VueRouter from 'vue-router' // 引入VueRouter
import About from '../components/About' // 路由组件
import Home from '../components/Home' // 路由组件
// 创建router实例对象,去管理一组一组的路由规则
const router = new VueRouter({
routes:[
{
path:'/about',
component:About
},
{
path:'/home',
component:Home
}
]
})
//暴露router
export default router
src/main.js:
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router' // 引入VueRouter
import router from './router' // 引入路由器
Vue.config.productionTip = false
Vue.use(VueRouter) // 应用插件
new Vue({
el:'#app',
render: h => h(App),
router:router
})
浏览器会被替换为a标签About 注意:
$route属性,里面存储着自己的路由信息$router属性获取到配置路由规则,使用children配置项:
routes:[
{
path:'/about',
component:About,
},
{
path:'/home',
component:Home,
children:[ // 通过children配置子级路由
{
path:'news', // 此处一定不要带斜杠,写成 /news
component:News
},
{
path:'message', // 此处一定不要写成 /message
component:Message
}
]
}
]
<!-- 跳转并携带query参数,to的模板字符串写法 -->
<router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">跳转</router-link>
<!-- 跳转并携带query参数,to的对象写法(推荐) -->
<router-link
:to="{
path:'/home/message/detail',
query:{
id: m.id,
title: m.title
}
}"
>跳转</router-link>
作用:可以简化路由的跳转
如何使用:
{
path:'/demo',
component:Demo,
children:[
{
path:'test',
component:Test,
children:[
{
name:'hello' // 给路由命名
path:'welcome',
component:Hello,
}
]
}
]
}
<router-link
:to="{
name:'hello',
query:{
id:666,
title:'你好'
}
}"
>跳转</router-link>
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News
},
{
component:Message,
children:[
{
name:'xiangqing',
path:'detail/:id/:title', // 🔴使用占位符声明接收params参数
component:Detail
}
]
}
<router-link
:to="{
name:'xiangqing',
params:{
id:666,
title:'你好'
}
}"
>跳转</router-link>
$route.params.id
$route.params.t
props作用:让路由组件更方便的收到参数
src/router/index.js:
{
name:'xiangqing',
path:'detail/:id',
component:Detail,
//第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
// props:{a:900}
//第二种写法:props值为布尔值,为true时,则把路由收到的所有params参数通过props传给Detail组件
// props:true
//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
props($route){
return {
id: $route.query.id,
title: $route.query.title
}
}
}
src/pages/Message.vue:父
<li v-for="m in messageList" :key="m.id">
<router-link :to="{
name:'xiangqing',
params:{
id:m.id,
title:m.title
}
}">
{{m.title}}
</router-link>
src/pages/Detail.vue:子
<template>
<ul>
<li>消息编号:{{ id }}li>
<li>消息标题:{{ title }}li>
ul>
template>
<script>
export default {
name:'Detail',
props:['id','title']
}
script>
router-link属性:
路由跳转的 replace 方法
1。作用:控制路由跳转时操作浏览器历史记录的模式
2。浏览器的历史记录有两种写入方式:push和replace
push是追加历史记录
replace是替换当前记录,路由跳转时候默认为push方式
3。开启replace模式
简写
总结:浏览记录本质是一个栈,默认push,点开新页面就会在栈顶追加一个地址,后退,栈顶指针向下移动,改为replace就是不追加,而将栈顶地址替换
编程式:
作用:不借助实现路由跳转,让路由跳转更加灵活
this.$router.push({}) 内传的对象与中的to相同
this.$router.replace({})
this.$router.forward() 前进
this.$router.back() 后退
this.$router.go(n) 可前进也可后退,n为正数前进n,为负数后退
methods:{
showPush(m){
this.$router.push({
name:'xiangqing',
query:{
id:m.id,
title:m.title
}
})
},
作用:让不展示的路由组件保持挂载,不被销毁
// 缓存一个路由组件
<keep-alive include="News"> // include中写想要缓存的组件名,不写表示全部缓存
<router-view></router-view>
</keep-alive>
// 缓存多个路由组件
<keep-alive :include="['News','Message']">
<router-view></router-view>
</keep-alive>
activated和deactivated是路由组件所独有的两个钩子,用于捕获路由组件的激活状态
具体使用
作用:对路由进行权限控制
分类:全局守卫、独享守卫、组件内守卫
全局守卫:
router:
// 全局前置守卫:初始化时、每次路由切换前执行
router.beforeEach((to,from,next) => {
console.log('beforeEach',to,from)
if(to.meta.isAuth){ // 判断当前路由是否需要进行权限控制
if(localStorage.getItem('school') === 'atguigu'){ // 权限控制的具体规则
next() // 放行
}else{
alert('暂无权限查看')
}
}else{
next() // 放行
}
})
// 全局后置守卫:初始化时、每次路由切换后执行
router.afterEach((to,from) => {
console.log('afterEach',to,from)
if(to.meta.title){
document.title = to.meta.title //修改网页的title
}else{
document.title = 'vue_test'
}
})
独享路由守卫:
路径下:
beforeEnter(to,from,next){
console.log('beforeEnter',to,from)
if(localStorage.getItem('school') === 'atguigu'){
next()
}else{
alert('暂无权限查看')
}
}
组件内守卫:
写在组件内:
//进入守卫:通过路由规则,进入该组件时被调用
beforeRouteEnter (to, from, next) {... next()},
//离开守卫:通过路由规则,离开该组件时被调用
beforeRouteLeave (to, from, next) {... next()},
hash和history
const router = new VueRouter({
mode:'history',
//mode:'hash',
routes:[...]
})
export default router
npm run build:转成css、html、js