=> 常见vue面试题, 持续更新ing...
生命周期
vue2
- beforcreate, create, beformount, mounted, beforupdate, updated, befordestroy, destroyed
vue3
- vue3中没有了beforcreate, create被setup替代了
- 销毁时的生命周期改变了: befordestroy => onBeforeUnmount. destroyed => onUnmounted
- 其余的在前面加了on: onBeformount, onMounted, onBeforupdate, onUpdated
create 和 mounted的区别
- create: 在模板渲染成html前调用, 通常用于初始化某些值
- mounted: 在模板渲染成html后调用,初始化页面完成,可以对dom节点进行操作
computed 和 watch
- computed:
- 计算属性,会将变化存到缓存中,直到依赖数据改变才会重新计算,但是不支持异步
- 与方法对比: 方法无论依赖数据是否改变,都会重新运行一次,相比之下计算属性在数据不变的情况下性能会更好
- 应用举例: 获取数据A都需要进行一次消耗性能的遍历,而数据B依赖于数据A,那么在数据没有改变的情况下使用计算属性会更好,避免的调用方法导致的每次都要遍历
// html
<p>{{ testSchool }}</p>
// script
<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, computed } from 'vue'
// 引入testInterface接口
import { testInterface } from '@/interface/use'
// 定义一个对象数据继承testInterface接口
const obja: testInterface = reactive({
name: 'school',
class: [1,2,3,4,5,6]
})
// 定义变量,接收计算属性
const testSchool = computed(() => {
// 如果数组长度改变,就会进行判断
return obja.class.length > 0 ? 'yes' : 'no'
})
</script>
- watch
- watch: 不支持缓存,但是支持异步操作
- 使用场景: 当数据变化时需要执行异步或开销较大时使用
父子组件生命周期
- 父子组件声明周期分为三个阶段
- 创建阶段: 父组件beforcreate -> 父组件create -> 父组件beformount -> 子组件beforcreate -> 子组件create -> 子组件beformount -> 子组件mounted -> 父组件mounted
- 数据更新阶段: 父组件的beforupdate -> 子组件的beforupdate -> 子组件的updated -> 父组件的updated
- 销毁阶段: 父组件的befordestroy -> 子组件的befordestroy -> 子组件的destroyed -> 父组件的destroyed