Vue3 引导大家使用 setup 方法以同步的方式组织逻辑,实质上编写方式与2.X时代发生了巨大变化。同步意味着 setup 方法中无法使用 this( this 并不指向当前组件实例 ),我们需要使用 vue3 中暴露出来的方法来实现vue的一些功能 (比如computed)如下:
<script setup>
import {computed,ref} from 'vue'
const num = ref(10)
const status = computed(()=>num.value <= 10 ? true : false)
//...
//使用了 setup 语法糖
//文档 https://github.com/vuejs/rfcs/blob/script-setup-2/active-rfcs/0000-script-setup.md
//使用 setup() 也是一样的
</script>
语法(思路)变更后,虽然大多数情况确实不再需要 this ,但还是有情况需要的,比如DOM操作,需要用到 $refs 方法的时候。这个方法目前没有如上方式被暴露出来,又因为 vue 新提供了一个叫 ref的方法(代替object类型以外的data的声明)与其同名导致相关文档我是怎么也没查到…
实际上解决办法是使用getCurrentInstance 方法 ,得到主组件的实例.
再从中获取proxy对象 得到当前组件实例
<script setup>
import {getCurrentInstance} from 'vue'
const {proxy} = getCurrentInstance()
console.dir(proxy)
</script>