vue3---getCurrentInstance

In the parent component:

1. Import subcomponents in setup syntax sugar
2. Bind the ref value on the subcomponent tag
3. Export the getCurrentInstance method from Vue as needed within setup
4. Call the getCurrentInstance method to export proxy
5. Through proxy.$refs.subcomponent ref Name. Attribute/method implementation call in subcomponent

<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'));

Method 1: Obtain the current component instance through the getCurrentInstance method to obtain route and 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>

Method 2: Use route and router by importing useRoute useRouter from routing. Official 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)
}
})

Guess you like

Origin blog.csdn.net/qq_46199553/article/details/127878557