vue2中的this.$el,this.$parent,this.$children 在vue3中如何表示

今天在从vue2升级vue3的时候,遇到了这个问题,下面说一下这些怎么表示

vue2中的this.$el其实就是获取当前的组件节点,让我们来看一下代码和输出

在vue2中我们有组件:

<template>
  <div class="aaa">
    <div class="block">
      <span class="demonstration">完整功能</span>
    </div>
  </div>
</template>

<script>
export default {
  name: '',
  data() {
    return {}
  },
  mounted() {
    console.log(this.$el, 'this.$el')
  },
}
</script>

<style lang="" scoped></style>

看一下输出是什么

通过 class="aaa" 可以看见输出就是当前模板标签内的根标签

所以在 vue3 中我们可以通过在 ref 的方式获取到根标签,代码如下

<script setup lang="ts">
import { ref } from 'vue'
const ownInstance = ref(null)

console.log(ownInstance, 'ownInstance')
</script>
<template>
  <div ref="ownInstance" class="aaa">
    <div class="block">
      <span class="demonstration">完整功能</span>
    </div>
  </div>
</template>

<style lang="less" scoped></style>

之后我们在看一下 vue2 里面的 this.$parent 输出的是什么

输出的是它的父组件,我们在vue3中获取父组件是这样的

import { getCurrentInstance } from 'vue'

const instance = getCurrentInstance()

console.log(instance.parent)

让我们来看一下输出是什么样子的

这里要注意的是,当需要使用父组件里面的一些方法或者数据时,需要在 exposed 里面使用

然后在说一下 this.$children,在vue2中,this.$children 就是获取子组件的实例,vue3 我们可以通过 ref 获取

<template>
  <ChildComponent ref="childRef" />
</template>

<script lang="ts">
import { ref, onMounted } from 'vue'
import ChildComponent from './ChildComponent.vue'
const childRef = ref(null)

onMounted(() => {
  // 访问子组件实例
  console.log(childRef.value)
})
</script>

但是有个地方我们注意一下:

当在 vue2 根据 this.$children 获取到的子组件是一个数组,而在 vue3 中通过 ref 获取到的子组件,如果只有一个 ref=xxx,获取到的 xxx 就是一个子组件实例,当有多个 ref=xxx 的时候,获取到的才是数组,下面来看一下详细的

vue2只有一个子组件时:

<template>
  <div class="aaa">
    <div class="block">
      <span class="demonstration">完整功能</span>
      <testxxx></testxxx>
      <!-- <testxxx v-for="i in 3" :key="i"></testxxx> -->
    </div>
  </div>
</template>

<script>
import testxxx from './testxxx.vue'
export default {
  name: '',
  components: { testxxx },
  data() {
    return {}
  },
  mounted() {
    console.log(this.$children, 'this.$children')
  },
}
</script>

<style lang="" scoped></style>

vue2有多个子组件时:

vue3只有一个子组件时:

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import trimxxx from './trimxxx.vue'
const childRef = ref(null)

onMounted(() => {
  // 访问子组件实例
  console.log(childRef.value)
})
</script>

<template>
  <!-- <trimxxx ref="childRef" /> -->
  <trimxxx ref="childRef" v-for="i in 3" :key="i" />
</template>

<style scoped></style>

vue3有多个子组件时:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值