总结
Vue3优点
- diff算法的优化,hoistStatic静态提升(对于不参与更新的元素,在渲染时直接复用)
- cacheHandlers 事件侦听器缓存:vue2中绑定事件每次触发都会重新生成新的function,vue3中利用cacheHandlers提供事件缓存对象
- 对于ts更好的支持
- 更方便、先进的组件,支持多根节点组件
- 组合API/注入API,能够更好的组织逻辑,封装逻辑,复用逻辑
- 按需编译,体积更小
vite优缺点
优点:
- Vite开发环境下速度更快,体验好
- Vite支持多种框架,Vue,React等
缺点:
- 只支持ES6浏览器
- 脚手架不包括Vuex,Router等
script setup
是vue3中引入的语法糖,为了简化Composition API冗长的模板代码
- 关于setup讲解:
https://zhuanlan.zhihu.com/p/471806345
生命周期函数和钩子函数对比
beforeCreate -> setup()
created -> setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
activated -> onActivated
deactivated -> onDeactivated
errorCaptured -> onErrorCaptured
$emit
- 在 script setup 中必须使用 defineProps 和 defineEmits API 来声明 props 和 emits
<!-- 无默认值 -->
const props = defineProps<{
foo: string
bar?: number //非必传
}>()
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string): void
}>()
// 有默认值
interface Props {
value: number
theme: string
}
const props = withDefaults(defineProps<Props>(), {
value: 0,
theme: 'blue'
})
reactive和ref定义变量时的区别
- reactive定义复杂的数据类型的数据,ref推荐定义基本数据类型,所以如果要使用reactive定义基本数据类型的话,我们需要在reactive中将数据包装一下
- 在JS中访问ref的值需要手动添加.value,访问reactive不需要
- reactive的底层响应式原理是Proxy,ref的原理是defineProperty
引用js文件时报错无法找到模块“@/xxx/xxx”的声明文件
使用 require引用
const { formulaEditor } = require("@nr/formulaeditor")
watch监听
<!-- 监听基本类型 -->
const nums = ref(9)
watch(nums, (newValue, oldValue) => {
console.log('watch 已触发', newValue)
})
<!-- 监听复杂类型 -->
watch(demo, (newValue, oldValue) => {
console.log('watch 已触发', newValue)
})
- 关于watch: https://zhuanlan.zhihu.com/p/465651353
$refs
1、利用defineExpose调用
const childRef=ref()
<!-- 需要在挂在完成之后才能正常使用 -->
onMounted(() => {
console.log(childRef.value); // Proxy {…}
});
<!--在子组件中还需要将子组件内的方法向外暴露,父组件才可以调用 -->
const foo = () => {
console.log("foo");
}
defineExpose({
foo
});
// 调用子组件方法
childRef.value.foo(); // foo
2、利用getCurrentInstance(官方不推荐使用此方法代替获取this)
根据官方文档,getCurrentInstance支持访问内部组件实例
getCurrentInstance 只能在 setup 或生命周期钩子中调用
如需在 setup 或生命周期钩子外使用,请先在 setup 中调用 getCurrentInstance() 获取该实例然后再使用。
const MyComponent = {
setup() {
const internalInstance = getCurrentInstance() // 有效
const id = useComponentId() // 有效
const handleClick = () => {
getCurrentInstance() // 无效
useComponentId() // 无效
internalInstance // 有效
}
onMounted(() => {
getCurrentInstance() // 有效
})
return () =>
h(
'button',
{
onClick: handleClick
},
`uid: ${id}`
)
}
}
// 在组合式函数中调用也可以正常执行
function useComponentId() {
return getCurrentInstance().uid
}