【问题标题】:this.$refs, this.$router, this.$route access with Vue 2 Composition APIthis.$refs, this.$router, this.$route 使用 Vue 2 组合 API 访问
【发布时间】:2021-06-02 18:38:02
【问题描述】:
您能告诉我如何在 Vue 2 组合 API 设置功能中访问 this.$refs、this.$router、this.$route 吗? context.$root 提到了一些解决方案,但 $root 不再适用于 context。请帮忙。
我正在使用带有 Composition API 插件的 Vue 2。 useRoute 或 useRouters 似乎不支持 Vue 2 路由器版本。 useRoute 和 useRouters 可用于 Vue-router v4。
【问题讨论】:
标签:
vue.js
vuejs2
vue-component
vue-router
vue-composition-api
【解决方案1】:
您可以从其模块中导入路由器并从中访问router 和route。
可以像在 Vue 3 中一样使用 Refs:
import { ref, onMounted } from "@vue/composition-api"; // import ref, onMounted
import router from "@/router"; // import router
export default {
setup() {
console.log(router); // this.$router
console.log(router.app.$route); // this.$route
const myref = ref(null); // create ref
onMounted(() => {
console.log(myref); // this.$refs.myref
});
return { myref }; // return for template ref
},
};