首页 > 其他分享 >Vue3 中的组件 provide和inject 传值、获取组件实例的方法getCurrentInstance()

Vue3 中的组件 provide和inject 传值、获取组件实例的方法getCurrentInstance()

时间:2023-01-07 22:14:29浏览次数:39  
标签:vue provide getCurrentInstance num inject 组件

 一、 provide和inject

  1:在父级组件中提供数据

          语法:provide('提供给子组件的变量名',提供给子组件的数据)

      2: 在子级组件中获取收据

          语法:let nums=inject('父组件传过来的变量名')  

二、在Vue3中获取组件实例的方法getCurrentInstance(),需要在父组件中暴露传给父组件的属性或方法defineExpose()

  在vue2中获取组件的实例 this

案例

父组件:

<template>
  <div>
    <h2>组件的数据传递 provider 和 inject</h2>
    <!-- 
      1:在父级组件中提供数据
          语法:provide('提供给子组件的变量名',提供给子组件的数据) 
      2: 在子级组件中获取收据
          语法:let nums=inject('父组件传过来的变量名');
    -->
    <BackTop></BackTop>
    <Winput></Winput>
  </div>
</template>

<script setup>
import BackTop from "./HeightComponent/BackTop.vue"
import Winput from "./HeightComponent/Winput.vue"
import { ref, provide } from 'vue';

let num = ref("200");
provide('num', num)

// 让其他组件可以获取到得数据 => 将它暴露出去
const getF=()=>{
  console.log(100);
}
defineExpose({
  num,getF
})

</script>

<style>

</style>

// 子组件1 BackTop

<template>
<!-- 
    项目中高频使用的组件
        注册成 全局组件
        语法: App.component('组件名称',组件)
        vue项目中 组件 形式  1)vue 文件 =>{}
 -->
 <div>
    返回头部 {{nums}}
 </div>
</template>

<script setup>
    import {inject} from 'vue'
    let nums=inject('num');
   
</script>

<style scoped>

</style>

// 子组件2 Winput

<template>
    <div>input</div>
</template>

<script setup>
   import { getCurrentInstance } from 'vue';
   // 1 搜索到组件他的父亲组件 => app.vue
   // 2 在搜索组件中获取到父组件中得一些方法和属性
   // 获取当前组件实例vue2 this  vue3 => getCurrentInstance
   let {ctx}=getCurrentInstance();
   console.log(ctx);
   console.log(ctx.$parent);
</script>
   
<style scoped>
   
</style>

 

标签:vue,provide,getCurrentInstance,num,inject,组件
From: https://www.cnblogs.com/chccee/p/17033651.html

相关文章