vue3通过当前组件的实例获取路由或vuex

Vue 3.0 中通过 getCurrentInstance 方法获取当前组件的实例,然后通过 ctx 属性获得当前上下文。

const { ctx } = getCurrentInstance();

获取当前路由:

ctx.$router 是 Vue Router 实例,里面包含了 currentRoute 可以获取到当前的路由信息

vue3获取路由
<template>
    <section></section>
</template>

<script>
import { getCurrentInstance } from "vue";
export default {
    setup() {
        const { ctx } = getCurrentInstance();
        console.log("ctx=>", ctx.$router.currentRoute.value);
        return {};
    },
};
</script>

<style lang="scss">
</style>

获取vuex

vue3通过当前组件的实例获取路由或vuex
<template>
    <section></section>
</template>

<script>
import { getCurrentInstance } from "vue";
export default {
    setup() {
        const { ctx } = getCurrentInstance();
        console.log("ctx=>", ctx);
        console.log("store=>", ctx.$store);
        const update = () => {
            ctx.$store.commit("setTestNumber", 1);
        };
        return {
            update,
        };
    },
};
</script>

<style lang="scss">
</style>

类似文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注