2-3-6 Vue3 其他hooks
Posted 沿着路走到底
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2-3-6 Vue3 其他hooks相关的知识,希望对你有一定的参考价值。
Expose
向外部`ref` 暴露内部成员。
export default
setup(props, expose )
const reset = () =>
// Some reset logic
// Expose can only be called once.
// If you need to expose multiple properties, they must all
// be included in the object passed to expose.
expose(
reset
)
return () => <div />
Provide / Inject
`provide`为`vue` 的组件提供上下文(context)。`inject` 从上下文中获取信息。
import provide, defineComponent, inject from 'vue'
type User =
avatar : string
const TitleBar = defineComponent(
setup: () =>
const user = inject('user') as User
return () => (
<header>
<img src=user.avatar />
</header>
)
,
)
const Page = () =>
return <TitleBar />
export const ProvideExample = defineComponent(
setup : () =>
provide('user',
avatar : "https://v3.vuejs.org/logo.png"
)
return () =>
return <Page />
)
生命周期钩子
- setup(beforeCreate, created)
- onBeforeMount
- onMounted
- onBeforeUpdate
- onUpdated
- onBeforeUnmount
- onErrorCaptured
- onRenderTracked
- onRenderTriggered
- onActivated
- onDeactivated
用法类似这样:
export default
setup()
// mounted
onMounted(() =>
console.log('Component is mounted!')
)
特别解释:
**onActivated**
**onDeactivated**
上面两个是在Keep-Alive组件(vue的一种缓存机制,不会真的将组件`unmount` )时发生。
import KeepAlive, defineComponent, onActivated, ref from 'vue'
const Foo = defineComponent(
props :
name :
type : String
,
setup : (props) =>
onActivated(()=>
console.log(props.name, "activated")
)
return () =>
return <div>props.name</div>
)
const Switch = (toggle : toggle:boolean) =>
return (
<>
<KeepAlive>toggle && <Foo name="A" /></KeepAlive>
<KeepAlive>!toggle && <Foo name="B" /></KeepAlive>
</>
)
export const KeepAliveExample = defineComponent(
setup:() =>
const toggle = ref(false)
return () => <div>
<button onClick=() => toggle.value = !toggle.value>toggle</button>
<Switch toggle=toggle.value />
</div>
)
**onRenderTriggered**
**onRenderTracked**
这两个API追踪reactive值的trigger和track行为。见具体的示例。
import defineComponent, ref, onRenderTracked, onRenderTriggered from 'vue'
export const TrackExample = defineComponent(
setup : () =>
const count = ref(0)
onRenderTriggered(e =>
console.log('trigger', e)
)
onRenderTracked(e =>
console.log('track', e)
)
setInterval(() =>
count.value ++
, 1000)
return () => <div>
count.value
</div>
)
1
以上是关于2-3-6 Vue3 其他hooks的主要内容,如果未能解决你的问题,请参考以下文章
在 react 里写 vue3 ? 还写了自定义 hooks和 Hoc 构建了响应式 !