前言
各位掘友好,我是庚云。作为我司的前端二面面试官,在考察候选人时,除了技术深度,我通常会比较关注候选者的主动学习能力。准备面试和日常工作,这些在我看来都算是被动式学习。候选者不学就找不到工作,或者无法胜任目前的工作对吧,所以我认为这种都属于被动式学习。我更喜欢能主动学习的候选者,比如会关注社区技术趋势,学习新技术,写学习笔记这样的候选者。代表候选者对技术有一定追求。这种人,将来一起共事的时候,省心省力❤
废话不多说,下面分享我最近必问的3个问题
一、vue3.5 props响应式有哪些变化?
- vue3 需要配合使用toRefs或者toRef 解构,才能保持响应式。
//index.vue
<input v-model="msg" style="width: 300px" />
<child :msg="msg" ref="childRef"/>
import { ref } from "vue':
const msg = ref('');
// child.vue
<div class="green">{{ msg J}</div>
import { watch, toRef } from 'vue';
const props = defineProps([ 'msg' ]);
const msg = toRef(props,'msg');
watch(msg, () => {
console.log('watch msg:', msg.value;
});
- vue3.5 直接进行解构赋值,响应式会保留。
//index.vue
<input v-model="msg" style="width: 300px" />
<child :msg="msg" />
import { ref } from "vue':
const msg = ref('');
//child.vue
<div class="green">{{ msg }}</div>
import { watch } from 'vue';
const { msg } = defineProps([ 'msg' ])
watch(() => msg, () => {
console.log('watch msg:', msg);
});
二、vue3.5 新增的useTemplateRef是做什么用的?
- vue3 需要通过定义一个
ref(null)引用一个组件,但这样对语义化层面理解不太友好
//index.vue
<child ref="childRef"/>
<button @click="handler()">getMsg</button>
import { ref } from 'vue';
import child from '. /components/child.vue'
const childRef = ref(null);
function handler() {
console.log('msg:', childRef.value.getMsg());
}
// child.vue
function getMsg(){
return 'I am message';
}
defineExpose({
getMsg
});
- vue3.5 新增了
useTemplateRef方法作为模板引用,语义化更好。
//index.vue
<child ref="childRef"/>
<button @click="handler()">getMsg</button>
import { useTemplateRef } from 'vue';
import child from './components/child.vue'
const childRef = useTemplateRef('childRef')
function handler() {
console.log('msg:', childRef.value.getMsg());
}
//child.vue
function getMsg() {
return 'I am message';
}
defineExpose({
getMsg
);
三、vue3.5 watch deep 有哪些更新?
- vue3 要深度监听一个对象,只能设置{deep:true},但部分业务场景下,并不需要完全深度监听,业务 只会影响到第二或第三层,这种情况下深度监听会性能代价是非常昂贵的。
<button @click="handler()">change</button>
import { ref, watch } from 'vue';
const obj = ref({
a: {
b:{
C:
d:
)
}
}
})
watch(obj,() => {
console.log('watch obj change');
},{ deep: true });
const handler = () =>
obj.value.a.b.c.d = Math.random() ;
};
- vue3.5 中deep配置可支持传入一个 number 类型,指代只监听到第n 层。
<button @click="handler ()">change</button>
import { ref, watch } from 'vue';
const obj = ref({
a: {
b:{
C:
d:
)
}
}
})
watch(obj, () => {
console.log('watch obj change');
},{ deep: 2 });
const handler = () => {
obj.value.a.b = Math.random() ;
};