vue3.x篇四——vue router和vuex的使用

41 篇文章 0 订阅
15 篇文章 0 订阅

vue3.x搭载的是vue-router 4vuex 4
本节代码demo地址:demo项目链接

1、demo图

在这里插入图片描述

2、vue-router的用法

首先要引入vue-router暴露的api

import { useRoute, useRouter } from "vue-router";

然后在setup()函数中做相应操作

setup(){
	const route = useRoute();
    const router = useRouter();
    const curRouterPath = router.currentRoute.value.path;
    const backRouterPath = router.options.history.state.back;
}

3、vuex的用法

首先要引入vuex暴露的api

import { useStore } from "vuex";

然后在setup()函数中做相应操作

setup(){
	const store = useStore();
    // const hitNum = computed(() => store.state.test.hit);
    const hitNum = computed(() => store.getters["test/getHit"]);
    const handleClick = () => {
      let num = store.state.test.hit;
      store.dispatch("test/setHit", ++num);
    };
}

4、还有一种获取方式,利用getCurrentInstance。但是开发环境可以,生产环境报错

我在这里也记录一下

import { getCurrentInstance} from "vue";
import { getCurrentInstance, computed } from "vue";

export default {
  setup() {
    const { ctx } = getCurrentInstance();
    /*路由*/
    const curRoutePath = ctx.$router.currentRoute.value.path;
    /*vuex*/
    const hitNum = computed(() => ctx.$store.state.test.hit);
    return {
      curRoutePath,
      hitNum
    };
  }
};

学习笔记,以供参考,如有问题欢迎赐教!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值