但是,如果我们想要访问当前组件的实例对象,那该怎么办呢?我们可以引入getCurrentInstance这个api,返回值就是当前组建的实例!
import { computed, getCurrentInstance } from "@vue/composition-api";
export default {
name: "svg-icon",
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String
}
},
setup(initProps,setupContext) {
// ⚠️注意,如果是通过vue add vue-next添加的这个地方需要结构出ctx
const ctx = getCurrentInstance();
const iconName = computed(() => {
return `#icon-${initProps.iconClass}`;
});
const svgClass = computed(() => {
if (initProps.className) {
return "svg-icon " + initProps.className;
} else {
return "svg-icon";
}
});
return {
iconName,
svgClass
};
}
};
</script>Ref自动展开(unwrap)
ref() 函数用来根据给定的值创建一个响应式的数据对象,ref() 函数调用的返回值是一个被包装后的对象(RefImpl),这个对象上只有一个 .value 属性,如果我们在setup函数中,想要访问的对象的值,可以通过.value来获取,但是如果是在<template>模版中,直接访问即可,不需要.value!
import { ref } from '@vue/composition-api'setup() {
const active = ref("");
const timeData = ref(36000000);
console.log('输出===>',timeData.value)
return {
active,
timeData
}
}
<template>
<p>活动状态:{{active}}</p>
<p>活动时间:{{timeData}}</p>
</template>⚠️注意:不要将Array放入ref中,数组索引属性无法进行自动展开,也不要使用 Array 直接存取 ref 对象:
const state = reactive({
list: [ref(0)],
});
// 不会自动展开, 须使用 `.value`
state.list[0].value === 0; // truestate.list.push(ref(1));
// 不会自动展开, 须使用 `.value`
state.list[1].value === 1; // true
当我们需要操作DOM的时候,比如我们在项目中使用swiper需要获取DOM,那么我们还可以这样�!
<div class="swiper-cls">
<swiper :options="swiperOption" ref="mySwiper">
<swiper-slide v-for="(img ,index) in tabImgs.value" :key="index">
<img class="slide_img" @click="handleClick(img.linkUrl)" :src="img.imgUrl" />
</swiper-slide>
</swiper>
</div>然后在setup函数中定义一个const mySwiper = ref(null);,之前在vue2.x中,我们是通过this.$refs.mySwiper来获取DOM对象的,现在也可以使用ref函数代替,返回的mySwiper要和template中绑定的ref相同!










