Vue的路由守卫与Store

路由守卫

全局路由守卫

router.beforeEach((to, from, next) => {
    console.log("去哪:", to, "那来:", from);
    // sessionStorage.getItem()
    //是否运行放行
    next();
})
//后置路由守卫
router.afterEach((to, from)=>{
    console.log("后置路由守卫:去哪:", to, "那来:", from);
})

独享路由守卫

beforeEnter: (to: any, from: any, next: any) => {
console.log("独享路由守卫:去哪:", to, "那来:", from);
//是否放行
next();
}

组件路由守卫

<script lang="ts">
export default {
  name: "Detail",
  beforeRouteEnter(to, from) {
    console.log("在渲染该组件的对应路由被验证前调用")
    // 不能获取组件实例 `this` !
    // 因为当守卫执行时,组件实例还没被创建!
  }
}
</script>
//组件路由守卫
onBeforeRouteUpdate((to, from) => {
  // console.log(to,from)
  console.log("当前路由被改变,如果同一个路径,但是参数不同 也可以重复触发");
})

onBeforeRouteLeave((to, from, next) => {
  console.log("通过路由规则,离开该组件时被调用:", to, from);
  //是否允许 离开
  next();
})

Pinia

Pinia 起始于 2019 年 11 月左右的一次实验,其目的是设计一个拥有组合式 API 的 Vue 状态管理库。从那时起,我们就倾向于同时支持 Vue 2 和 Vue 3,并且不强制要求开发者使用组合式 API,我们的初心至今没有改变。除了安装SSR 两章之外,其余章节中提到的 API 均支持 Vue 2 和 Vue 3。虽然本文档主要是面向 Vue 3 的用户,但在必要时会标注出 Vue 2 的内容,因此 Vue 2 和 Vue 3 的用户都可以阅读本文档。

安装:npm install pinia

配置:src/main.ts

//引入 pinia 的 createPinia 创建 pinia
import {createPinia} from "pinia";

//创建 pinia实例
const pinia = createPinia();

//载入pinia到vue中
app.use(pinia);

使用:

准备案例

Count.vue


<template>
  <div class="count">
    <h2>当前求和为:{{ sum }}</h2>
    <select v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="add">+</button>
    <button @click="minus">-</button>
  </div>
</template>

<script setup lang="ts" name="Count">
import {ref} from "vue";

//当前求和
let sum = ref(1);
//当前用户选择的数字
let n = ref(1);
const add = () => {
  sum.value += n.value;
}
const minus = () => {
  sum.value -= n.value;
}


</script>

<style scoped lang="css">
.count {
  background-color: skyblue;
  padding: 10px;
  border-radius: 10px;
  box-shadow: 0 0 10px;
}

select, button {
  margin: 0 5px;
  height: 25px;
}

</style>

Joke.vue

<template>
  <button @click="getJoke">获取笑话</button>
  <div class="joke" v-for="joke in jokeList" :key="joke.id">
    {{ joke.title }}
    <br/>
    {{ joke.content }}
  </div>

</template>

<script setup lang="ts" name="Joke">
import {reactive} from "vue";
import axios from "axios";

let jokeList = reactive([]);

const getJoke = async () => {
  let {data: {data: {content, title, id}}} = await axios.get("https://api.vvhan.com/api/text/joke?type=json");
  console.log(content, title, id)
  jokeList.unshift({id, title, content});
}
</script>

<style scoped>

.joke {
  margin-top:20px ;
  background-color: orange;
  padding: 10px;
  border-radius: 10px;
  box-shadow: 0 0 10px;
}
</style>

存储 + 读取数据

1.Store 是一个保存:状态、业务逻辑的实体,每个组件都可以读取、写入它。

它有三个概念:

state action getter 想等于组件中的:

data methods computed

1.创建Store配置文件

src/store/count.ts

import {defineStore} from 'pinia'



//创建并暴露 一个 Store
export const useCountStore = defineStore('count', {
    //状态
    state() {
        return {
            sum: 8,
            school: '猿究院',
            address: "北大街"
        }
    },
    //动作
    actions: {
        //定义方法  加
        increment(value: number) {
            // 定义业务逻辑
            if (this.sum < 10) {
                this.sum += value;
            }
        },
        decrement(value: number) {
            if (this.sum > 1) {
                this.sum -= value;
            }
        },
        changeData(sum: number, address: string) {
            this.sum = sum;
            this.address = address;
        }


    },
    //计算
    getters: {}
})




storeToRefs

作用:借用storeToRefs将store中的数据转换为ref对象,方便在模板中使用。

注意:

pinia提供storeToRefs只会将数据转换,而Vue的toRefs会转换store中的数据。

import {storeToRefs} from "pinia";

const jokeStore = useJokeStore()

let {jokeList} = storeToRefs(jokeStore);

 <div class="joke" v-for="joke in jokeList" :key="joke.id">
    {{ joke.title }}
    <br/>
    {{ joke.content }}
  </div>

getters

当state中的数据 ,需要经过处理在使用时,可以使用getters配置

//计算
getters: {
	bigSum: (state): number => state.sum * 10
}

使用
countStore.bigSum
let {bigSum} = storeToRefs(countStore);

$subscribe

通过 store的$subscribe() 方法侦听state的改变。

jokeStore.$subscribe((mutation, state) => {
  console.log("$subscribe",mutation, state);
})

store组合式写法

import {defineStore} from "pinia";
import {reactive} from "vue";
import axios from "axios";

export const useTalkStore = defineStore("talk", () => {

    const jokeList = reactive([]);

    async function getJoke() {
        let {data: {data: {content, title, id}}} = await axios.get("https://api.vvhan.com/api/text/joke?type=json");
        console.log(content, title, id)
        jokeList.unshift({id, title, content});
    }

    return {
        jokeList, getJoke
    }
});

使用 
// store 组合式写法
import {useTalkStore} from "@/store/joke2";

const talkStore = useTalkStore()

talkStore.getJoke()

console.log("talkStore :",talkStore.jokeList)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值