获取当前组件对应的DOM元素
vue2:
this.$el
- Vue实例的属性之一,表示当前Vue实例所对应的DOM元素。
- this.$el是在mounted中才会出现的,在created的时候是没有的
mounted() { // 获取当前Vue实例所对应的DOM元素 const el = this.$el; // 对DOM元素进行操作,例如添加样式类 el.classList.add('my-class'); }
vue3:
getCurrentInstance
Vue3.x中的核心方法:getCurrentInstance,用于获取当前组件的实例、上下文来操作router和vuex等。
<script setup>
import { getCurrentInstance } from 'vue';
// 获取当前组件实例
const instance = getCurrentInstance();
// 获取当前组件的上下文,下面两种方式都能获取到组件的上下文。
// 方式一,这种方式只能在开发环境下使用,生产环境下的ctx将访问不到
const { ctx } = getCurrentInstance();
// 方式二,此方法在开发环境以及生产环境下都能放到组件上下文对象(推荐)
const { proxy } = getCurrentInstance();
</script>
ctx 中包含了组件中由ref和reactive创建的响应式数据对象,以及以下对象及方法;
- proxy.$attrs
- proxy.$data
- proxy.$el
- proxy.$emit
- proxy.$forceUpdate
- proxy.$nextTick
- proxy.$options
- proxy.$parent
- proxy.$props
- proxy.$refs
- proxy.$root
- proxy.$slots
- proxy.$watch
获取当前组件的refs
vue2:
this.$refs
- 获取页面中所有含有ref属性的DOM元素
vue3:
getCurrentInstance
方法一:
<script setup>
import { getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();
onMounted(()=>{
// xxx为dom或者子组件上加的ref,fn为其上的方法
// 注意:此时没有定义xxx为ref,即没有const xxx = ref()这样的语句
proxy.$refs.xxx.fn();
})
</script>
方法二:
<script setup>
import { ref } from 'vue';
const xxx = ref()
onMounted(()=>{
// xxx为dom或者子组件上加的ref,fn为其上的方法
xxx.value.fn();
})
</script>
v-for循环中绑定ref
vue2:
<div v-for="(item,index) in list" :key="item.id" :ref="item.name"></div>
// 使用 console.log(this.$refs)
this.$refs.itemName[0]
vue3:
方法一:使用函数
<template>
<div>
<span v-for="item in list" :ref="setRefs"> {{ item }}</span>
</div>
</template>
<script setup>
import { onBeforeUpdate, ref } from 'vue';
const list = ref([{id:1,name:'a'},{id:2,name:'b'}]);
const refList = ref([]);
const setRefs = (item) => {
refList.value.push(item)
}
// 更新前需置空
onBeforeUpdate(() => {
refList.value = []
})
</script>
方法二:使用toRef
<template>
<div>
<span v-for="(item, index) in list" :key="index" :ref="setRefs(index)"> {{ item }}</span>
</div>
</template>
<script setup>
import { ref, toRef, onBeforeUpdate } from 'vue'
const list = ref([{id:1,name:'a'},{id:2,name:'b'}]);
const refs = []
const setRefs = (index) => {
const refValue = toRef(refs, index.toString())
return (el) => {
refValue.value = el
}
}
onBeforeUpdate(() => {
refs.length = 0
})
</script>
方法三:使用unRef
<template>
<div>
<span v-for="(item, index) in list" :key="index" ref="itemsRef"> {{ item }}</span>
</div>
</template>
<script setup>
const itemsRef = ref(null);
const list = ref([{id:1,name:'a'},{id:2,name:'b'}]);
onMounted(()=>{
const refList = unref(itemsRef);
refList[2].innerHTML='aaa';
})
</script>