Vue3 Composition API

vue3.0在7月发布了rc版本,vue-cli4.5后也支持选择vue3做为备选版本能够体验了,vue3的正式版本相必也不远了。学不动了呀!!!!
相比vue2.0版本(Option API),Composition API(组合API)算是3.0的重大变动之一了。vue

概述

Composition API 主要灵感来源于React Hooks,目的是经过一组低侵入式的、函数式的 API,使得咱们可以更灵活地「组合」组件的逻辑。react

示例

<template>
  <div>{{count}}</div>
  <button @click="addCount">添加</button>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';

export default defineComponent({
  name: 'App',
  setup () {
    const count = ref(0)
    const getCount = () => {
      count.value = Math.floor(Math.random() * 10)
    }
    const addCount = () => {
      count.value++
    }
    onMounted(() => {
      getCount()
    })

    return {
      count,
      addCount
    }
  }
});
</script>

``
Composition API顾名思义就是再也不传入data、mounted等参数,经过引入的ref、onMounted等方法实现数据的双向绑定、生命周期函数的执行。vue-cli

为何须要

1.在组件比较复杂的状况下,能够将逻辑代码合到一块儿去,而不会被option强行分隔。这提升了代码质量的上限,同时也拉低了代码质量的下限。来自官方的一张对比图:typescript

image

2.更好的进行复用。api

在vue2中,想要复用部分逻辑的代码,都是经过mixin进去。但mixin进去的内容实际上很不直观,并且相同命名会被覆盖。而经过composition API,由于全部的方法都是引入的,能够将单独某个逻辑进行封装。例如对发送验证码倒计时功能进行封装。数组

<template>
  <input type="number" placeholder="请输入验证码">
  <button v-if="count">{{count}}秒后可从新发送</button>
  <button v-else @click="startCount">发送验证码</button>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from 'vue';

const userCountDown = () => {
  const count = ref(0)
  const countDown = (num: number) => {
    count.value = num
    num--
    if (num > 0) {
      setTimeout(() => {
        countDown(num)
      }, 1000)
    }
  }
  const startCount = () => {
    // get verifyCode
    countDown(60)
  }

  return { count, startCount }
}

export default defineComponent({
  name: 'Home',
  setup () {
    const { count, startCount } = userCountDown()
    return { count, startCount }
  }
});
</script>

3.更好的typescript支持。不会再往vue原型上添加不少内容,而是经过引入的方式,类型定义会更清晰。dom

setup

setup是vue新增的一个选项,它是组件内使用Composition API的入口。setup是在建立vue组件实例并完成props的初始化以后执行。由于setup会在option api解析以前被调用,因此setup中的this会与options中得彻底不同。为了不混乱,在setup中不使用this。同时setup返回的值,能够在模板和其余option中使用。从设计上来讲,vue官方是将全部的事情在setup里完成。setup返回值链接的是template模板与方法。函数

ref、reactive

既然不在传入data,那么将数据建立和监听响应式就须要经过vue暴露出来的功能 ref或reactive。二者有所区别,ref用于基础赋值类型的数据,而reactive用于引用类型的数据。this

其中基础赋值类型的值,在setup方法中,须要用 .value的方式进行获取和修改。由于赋值类型的值若是return出去返回值,就失去了数据的双绑定。可是在template中,能够进行直接访问。spa

<template>
  <div>{{count}}
    <button @click="changeCount">添加</button>
  </div>
  <div>学生的姓名是:{{student.name}}</div>
  <div>学生的年龄是:{{student.age}}
    <button @click="changeStudentAge(20)">添加</button>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from 'vue';

export default defineComponent({
  name: 'Home',
  setup () {
    const count = ref(0)
    const changeCount = () => {
      count.value = count.value + 1
    }
    const student = reactive({
      name: 'Bob',
      age: 12
    })
    const changeStudentAge = (age: number) => {
      student.age = age
    }
    return {
      count,
      changeCount,
      student,
      changeStudentAge
    }
  }
});
</script>

computed与watch

<template>
  <div>{{count}}</div>
  <div>{{doubleCount}}</div>
  <button @click="addCount">添加</button>
</template>

<script lang="ts">
import { defineComponent, ref, computed, watchEffect, watch } from 'vue';

export default defineComponent({
  name: 'App',
  setup () {
    const count = ref(0)
    watch(count, () => { // 如多个则用数组的方式传入[count, count1]
      console.log('watch', count.value)
    })
    watchEffect(() => {
      console.log('watchEffect', count.value)
    })
    const addCount = () => {
      count.value++
    }
    const doubleCount = computed(() => {
      return count.value * 2
    })
    return {
      count,
      doubleCount,
      addCount
    }
  }
});
</script>

watch与watchEffect的差异是,watchEffect会立马执行,执行中被读取的响应式 数据会被观测。而watch只有在watch对象有变化时才会执行。

生命周期

  • beforeCreate -> 使用 setup()
  • created -> 使用 setup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeDestroy -> onBeforeUnmount
  • destroyed -> onUnmounted
  • errorCaptured -> onErrorCaptured
相关文章
相关标签/搜索