在 Vue 2 中,this 关键字代表当前组件实例。在组件的选项对象中,this 可以用于访问组件实例的属性、方法以及 Vue 实例的一些特定方法。
在Vue3中,我们发现this是undefined,那我们真的没法使用this了吗?vu3给我们提供了一个getCurrentInstance函数: 用于获取当前组件实例。身上有个ctx属性有点类似this,通过代码可以看到如何使用。
组件实例身上还有个proxy属性也基本相同,proxy.xxx = xxxx修改数据后-是动态修改的(数据页面都更新)
建议:vue3中已经不想让大家使用this了,直接通过变量名取值也是很方便的,
当然有喜欢用this的也可以使用这种方式,不过目前看来取到的值是只读的。
<template>
<div style="font-size: 14px">
<div>{
{myName1}}</div>
<div>{
{myName2}}</div>
<div>{
{myName3}}</div>
</div>
</template>
<script lang="ts">
// vue3.0版本语法
import { defineComponent, getCurrentInstance, ref } from "vue";
export default defineComponent({
name: "组件名",
setup() {
// console.log(this);// undefi