getCurrentInstance、页面中route和router的获取方式
getCurrentInstance()
在vue2中,可以通过this来获取组件实例,但是在vue3的setup函数中,无法通过this获取到组件实例,在setup函数中this的值是undefined,但是vue3提供了getCurrentInstance()来获取组件的实例对象;- const { ctx,proxy } = getCurrentInstance();
- console.log(typeof getCurrentInstance);
- console.log(getCurrentInstance(), typeof getCurrentInstance());
- console.log(proxy, typeof proxy);
- console.log(ctx, typeof ctx);
复制代码 输出结果:
可以看出,getCurrentInstance是一个方法,getCurrentInstance()是一个对象,ctx和proxy也是一个对象,ctx和proxy是getCurrentInstance()对象中的一个属性,通过解构赋值的方式拿到的,ctx是一个普通的对象,而proxy是一个proxy对象,两者里面都可以看到当前组件的data值和方法,可以使用proxy[属性名]去获取实例对象中的数据或者调用对象中的方法;
getCurrentInstance只能在setup函数或生命周期钩子函数中使用;
ctx对象和proxy对象的区别:
1、从getCurrentInstance方法中解构出来的ctx对象,只能在开发环境下使用,生产环境下ctx将访问不到(不推荐使用)
2、proxy对象在开发环境以及生产环境中都能拿到组件实例对象(推荐使用)
获取组件实例对象的方式
1、获取挂载到全局中的方法- const instance = getCurrentInstance()
- console.log(instance.appContext.config.globalProperties)
复制代码 2、利用proxy对象- const { proxy } = getCurrentInstance()
复制代码 获取route和router的方式
- 方法一:通过getCurrentInstance()方法获取到组件实例,从而获取到route和router
- import { getCurrentInstance } from "vue";
- const { proxy } = getCurrentInstance();
- proxy.$router.push({ path: "/home" }); // 实现路由跳转
- console.log("获取当前路由---》", proxy.$route)
复制代码
- 方法二:通过从vur-router中引入useRoute()、useRouter()方法来获取到route和router
- import { useRoute, useRouter } from 'vue-router'
- const router = useRouter();
- const route = useRoute();
- console.log('当前路由:', route)
- router.push({ path: "/home" });
复制代码 总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
来源:https://www.jb51.net/javascript/339886jmp.htm
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |