优点:
缺点:
是vue3中引入的语法糖,为了简化Composition API冗长的模板代码
beforeCreate -> setup()
created -> setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
activated -> onActivated
deactivated -> onDeactivated
errorCaptured -> onErrorCaptured
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(), {
value: 0,
theme: 'blue'
})
使用 require引用
const { formulaEditor } = require("@nr/formulaeditor")
const nums = ref(9)
watch(nums, (newValue, oldValue) => {
console.log('watch 已触发', newValue)
})
watch(demo, (newValue, oldValue) => {
console.log('watch 已触发', newValue)
})
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
}