首页IT科技vue3—getCurrentInstance

vue3—getCurrentInstance

时间2025-05-06 03:48:13分类IT科技浏览4411
导读:父组件中: 1.setup语法糖中导入子组件...

父组件中:

1.setup语法糖中导入子组件

2.在子组件标签上绑定ref值

3.setup内部从vue中按需导出 getCurrentInstance 方法

4.调用getCurrentInstance方法导出proxy

5.通过proxy.$refs.子组件ref名.子组件内属性/方法 实现调用 <template> <!-- 父组件 --> <div> <!-- 子组件 --> <Child ref="child" /> <button @click="changeChildren">子组件count+1</button> </div> </template> <script setup lang="ts" name="Father"> import { getCurrentInstance, ComponetInternalInstance,ref } from "vue"; import Child from "./zi.vue"; const child = ref(null) // as ComponetInternalInstance表示类型断言             ,ts时使用             。否则报错                  ,proxy为null const { proxy } = getCurrentInstance() as ComponetInternalInstance; function changeChildren() { proxy.$refs.child.count += 1; //也可以使用ref数据.value的形式调用: //child.value.count += 1 console.log(child.value.name) } </script> <style scoped></style>

main.js

import api from "./utils/api.js" import StringUtil from "./utils/StringUtil.js" app.config.globalProperties.api = api; app.config.globalProperties.StringUtil = StringUtil; import {getCurrentInstance } from vue; const { proxy } = getCurrentInstance(); console.log(proxy.api); console.log(proxy.StringUtil.isBlank(1));

方式一            、通过 getCurrentInstance 方法获取当前组件实例      ,从而获取 route 和 router

Html

<template> <div> </div> </template> <script> import { defineComponent, getCurrentInstance } from vue export default defineComponent({ name: About, setup(){ const { proxy } = getCurrentInstance() console.log(proxy.$root.$route) console.log(proxy.$root.$router) return {} } }) </script>

方式二:通过从路由中导入 useRoute useRouter 使用 route 和 router                  。 官方Api

Html

import { defineComponent } from ‘vue’

import { useRoute, useRouter } from ‘vue-router’

export default defineComponent({

setup () {

const $route = useRoute()

const

r

o

u

t

e

r

=

u

s

e

R

o

u

t

e

r

(

)

c

o

n

s

o

l

e

.

l

o

g

(

router = useRouter() console.log(

router=useRouter()console.log(

route)

console.log($router)

}

})

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
今日赚是真的吗(今日赚什么时候能提现-早上把自媒体平台工资提现,这是22年最后一次发工资,23年加油喽)