# 生命周期
在 3.x 版本中,可以使用相应的组合式 Api 调用生命周期(通过在生命周期钩子前添加 on
)
选项式 API | Hook inside setup |
---|
beforeCreate | Not needed* |
created | Not needed* |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeUnmount | beforeUnmount |
unmounted | onUnmounted |
errorCaptured | onErrorCaptured |
renderTracked | onRenderTracked |
renderTriggered | onRenderTriggered |
activated | onActivated |
deactivated | onDeactivated |
因为 setup
是围绕 beforeCreate
和 created
生命周期钩子运行的,所以不需要显式地定义它们。换句话说,在这些钩子中编写的任何代码都应该直接在 setup
函数中编写。
| <template> |
| <div> |
| <h1 id="test">{ { count } }</h1> |
| <button @click="handleEdit">+ 1</button> |
| </div> |
| </template> |
| <script> |
| import { |
| ref, |
| onBeforeMount, |
| onMounted, |
| onBeforeUpdate, |
| onUpdated, |
| onBeforeUnmount, |
| onUnmounted, |
| } from "vue" |
| export default { |
| setup() { |
| const count = ref(0) |
| function handleEdit() { |
| count.value++ |
| } |
| onBeforeMount(() => { |
| console.log("挂载前") |
| }) |
| onMounted(() => { |
| console.log("挂载完成") |
| }) |
| onBeforeUpdate(() => { |
| console.log("DOM更新前", document.querySelector("#test").innerHTML) |
| }) |
| onUpdated(() => { |
| console.log("DOM更新完成", document.querySelector("#test").innerHTML) |
| }) |
| onBeforeUnmount(() => { |
| console.log("卸载前") |
| }) |
| onUnmounted(() => { |
| console.log("卸载后") |
| }) |
| return { count, handleEdit } |
| }, |
| } |
| </script> |
# Provide / Inject
通常,当我们需要从父组件向子组件传递数据时,我们使用 props
。想象一下这样的结构:有一些深度嵌套的组件,而深层的子组件只需要父组件的部分内容。在这种情况下,如果仍然将 prop 沿着组件链逐级传递下去,可能会很麻烦。
对于这种情况,我们可以使用一对 provide
和 inject
。无论组件层次结构有多深,父组件都可以作为其所有子组件的依赖提供者。这个特性有两个部分:父组件有一个 provide
选项来提供数据,子组件有一个 inject
选项来开始使用这些数据。
parent.vue
| <template> |
| <div> |
| <children /> |
| </div> |
| </template> |
| <script> |
| import { reactive, provide } from "vue" |
| import children from "./children.vue" |
| export default { |
| setup() { |
| const list = reactive([ |
| { id: 1, title: "文章1", author: "作者1" }, |
| { id: 2, title: "文章2", author: "作者2" }, |
| { id: 3, title: "文章3", author: "作者3" }, |
| ]) |
| provide("list", list) |
| return { list } |
| }, |
| components: { |
| children, |
| }, |
| } |
| </script> |
children.vue
| <template> |
| <div> |
| <grandson /> |
| </div> |
| </template> |
| <script setup> |
| import grandson from "./grandson.vue" |
| </script> |
grandson.vue
l | <template> |
| <div>{ { list } }</div> |
| </template> |
| <script setup> |
| import { inject } from "vue" |
| const list = inject("list") |
| </script> |