【Vue3从零开始-第六章】6-8 compositionAPI中的生命周期函数、provide和inject、模板中的ref

164 阅读4分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第10天,点击查看活动详情

前言

上一篇的文章中,我们一起学习了compositionAPI中的watch和watchEffect的使用和区别,本篇文章中我们将一起学习compositionAPI中最后的一部分内容:生命周期函数、provide、inject、模板中的ref

生命周期函数

👆 【vue3从零开始】基础知识篇里面我们也有学习过生命周期函数,但是在compositionAPI中也给我们提供了类似的生命周期函数。

👉 在compositionAPI中的生命周期函数会与基础知识篇里面的有些许不同,有新增也有删减。

<script>
  const app = Vue.createApp({
    setup() {
      const {ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated} = Vue
      const message = ref('Hello World')
      
      onBeforeMount(() => {
        console.log('onBeforeMount')
      })

      onMounted(() => {
        console.log('onMounted')
      })

      onBeforeUpdate(() => {
        console.log('onBeforeUpdate')
      })

      onUpdated(() => {
        console.log('onUpdated')
      })

      const handleClick = () => {
        message.value = 'Hello JueJin'
      }

      return {message, handleClick}
    },
    template: `
      <div>
        <span @click="handleClick">{{message}}</span>
      </div>
    `
  });
  const vm = app.mount('#root');
</script>
  • compositionAPI中,生命周期函数也需要单独从Vue中解构出来使用。
  • onBeforeMount函数类似于基础篇中的beforeMount函数
  • onMounted函数类似于基础篇中的mounted函数
  • 以此类推,其他基础篇中的生命周期函数也只是在加了一个on前缀。
  • 还有beforeUnmountunmouted函数大家可以自己试试哦~

1.gif

由于setup函数的特性,setup函数执行时间是在beforeCreate函数created函数之间,这两个生命周期函数中需要执行的东西直接写在setup函数中就可以了,所以在compositionAPI中是没有beforeCreate函数created函数的。

除了基础篇的部分生命周期函数之外,compositionAPI中还新增了两个生命周期函数:onRenderTrackedonRenderTriggered

const {onRenderTracked, onRenderTriggered} = Vue
onRenderTracked(() => {
    console.log('onRenderTracked')
})

onRenderTriggered(() => {
    console.log('onRenderTriggered')
})
  • onRenderTracked函数表示每次渲染后重新收集响应式依赖。
  • onRenderTriggered函数表示每次触发页面重新渲染时自动执行。

2.gif

provide和inject

👆 在基础知识篇中,我们也一起学习过provide和inject的使用方法,主要就是组件和组件之间传递参数时使用的,可以跨组件去传参。

👉 在compositionAPI中也可以通过provide和inject方法去给组件传递参数。

const app = Vue.createApp({
    setup() {
      const {ref, provide} = Vue
      const message = ref('Hello World')
      provide('message', message)
      return { }
    },
    template: `
      <div>
        <child />
      </div>
    `
  });
  • 首先我们在根组件中使用provide方法,在provide方法里面是一个key、value的方式赋值的。
app.component('child', {
    setup(){
      const {inject} = Vue
      const message = inject('message')
      return {message}
    },
    template: `
      <div>
        <span>{{message}}</span>
      </div>
    `
  })
  • 然后我们在定义一个子组件,子组件中通过inject方法去接收根组件传递过来的值,并return给外部。

2.png

✍ 由于vue的特性原因,父组件传递给子组件的数据,在子组件中是不允许直接修改的,想要修改的话,必须调用父组件的方法,在父组件中去修改传递过来的数据值。

app.component('child', {
    setup(){
      const {inject} = Vue
      const message = inject('message')
      const handleClick = () => {
        message.value = 'Hello JueJin'
      }
      return {message, handleClick}
    },
    template: `
      <div>
        <span @click="handleClick">{{message}}</span>
      </div>
    `
  })

3.gif

👋 但是在compositionAPI中传递的数据,是可以直接修改的,那么要怎么避免这种问题出现呢?

setup() {
    const {ref, provide, readonly} = Vue
    const message = ref('Hello World')
    provide('message', readonly(message))
    provide('changeMessage', () => {
        message.value = 'Hello Vue.js'
    })
    return { }
},
  • 只需要在根组件中传递参数时,给参数添加一个readonly函数(此函数也是从Vue中解构出来的)。
  • 然后在定义一个修改数据值的方法,并用provide函数传递给子组件。

readonly函数也是从Vue中解构出来的,表示函数里面的数据值为只读状态不可修改。这样就可以避免子组件直接修改父组件的数据值了。

setup(){
    const {inject} = Vue
    const message = inject('message')
    const changeMessage = inject('changeMessage')
    const handleClick = () => {
        changeMessage()
    }
    return {message, handleClick}
},
  • 子组件中需要接收根组件传递过来的方法,并在触发点击事件时调用根组件修改数据值的方法。

4.gif

模板中的ref

💭 模板中的ref是以前在基础知识篇中学过的,是定义在DOM标签上的。

<div ref="hello">Hello World</div>

如果我们需要获取到某个DOM元素,就需要通过this.$refs.xxx的方式获取。

想要在compositionAPI中获取到DOM元素该怎么做呢?

setup() {
    const { onMounted, ref } = Vue
    const hello = ref(null)
    onMounted(() => {
        console.log(hello.value)
    });
    return {hello}
},
  • 首先我们定义和DOM元素中的ref值相同的变量值,并引用compositionAPI中的ref方法
  • compositionAPI中的ref方法中传入的是一个null,不需要给它定义值。
  • compositionAPI中的生命周期函数里面输出一下这个变量值,就可以看到控制台中的DOM元素被打印出来了。

3.png

总结

本篇文章主要是和大家一起学习了compositionAPI中的最后一部分知识点。了解了基础知识中的生命周期函数和compositionAPI中的生命周期函数的区别;了解了compositionAPI中组件间传参的方法:provide和inject,并引出了readonly方法表示只读类型;最后还了解了一下模板中的ref的使用方法。

compositionAPI的篇章就正式完结了,希望大家在看的同时也能学到更多,大家加油!!