前言
本文主要介绍 Vue3 API之getCurrentInstance、reactive、ref的语法及版本差异。
一、 getCurrentInstance
getCurrentInstance
这个函数来返回当前组件的实例对象,也就是当前vue
这个实例对象。
1.1 版本差异
Vue2
中,可以通过this
来获取当前组件实例;
Vue3
中,在setup
中无法通过this
获取组件实例,console.log(this)
打印出来的值是undefined
。在Vue3
中,getCurrentInstance()
可以用来获取当前组件实例
1.2 语法
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance()
二、reactive
reactive
是Vue3
中提供实现响应式数据的方法。
2.1 版本差异
在
Vue2
中响应式数据是通过defineProperty
来实现的。
在Vue3
响应式数据是通过ES6
的Proxy
来实现的。reactive
参数必须是对象(json/arr)
,如果给reactive
传递了其他对象,默认情况下修改对象,界面不会自动更新,如果想更新,可以通过重新赋值的方式。
2.2 语法
import { reactive } from "vue";
const loginFormState = reactive({
name: "",
pwd: "",
loading: false,
});
三、ref
3.1 版本差异
在
vue2
中,ref
获取一个dom
元素和实例对象。
在vue3
中,ref
是用来定义数据响应式。ref
可以接收基本数据类型,也可以是对象类型。
3.2 语法
// 基本数据类型:基本数据类型 ref 的处理方式还是 Object.defineProPerty() 的get()和set() 完成
import { ref} from "vue";
let loginFormRef = ref('vitian') // => console.log(loginFormRef.value) => vitian
loginFormRef.value = 'prince' // => console.log(loginFormRef.value) => prince
// 对象类型:对象类型的 ref 处理借助了 reactive函数(reactive函数的内部实现通过ES6的代理对象 Proxy )
let loginFormRef = ref({
name: "vitian",
pwd: ""
}) // => console.log(loginFormRef.value.name) => vitian
loginFormRef.value.name = 'prince' // => console.log(loginFormRef.value.name) => prince