美文网首页
Composition API

Composition API

作者: 欢欣的膜笛 | 来源:发表于2020-12-27 15:30 被阅读0次

从基于对象的编程(OOP)转向了函数式编程(FP)

ref 函数

接受一个参数,返回一个响应式对象

<template>
  <h1>{{count}}</h1>
  <h2>{{double}}</h2>
  <button @click="increase">+1</button>
</template>

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

export default defineComponent({
  name: 'Home',
  setup () {
    const count = ref(0)
    const increase = () => {
      count.value++
    }
    const double = computed(() => count.value * 2)

    return {
      count,
      increase,
      double,
    }
  }
})
</script>

reactive 函数

<template>
  <h1>{{data.count}}</h1>
  <h2>{{data.double}}</h2>
  <button @click="data.increase">+1</button>
</template>

<script lang="ts">
import { computed, defineComponent, reactive } from 'vue'
interface DataProps {
  count: number
  increase: () => void
  double: number
}

export default defineComponent({
  name: 'Home',
  setup () {
    const data: DataProps = reactive({
      count: 0,
      increase: () => data.count++,
      double: computed(() => data.count * 2)
    })

    return {
      data
    }
  }
})
</script>

toRefs 函数

<template>
  <h1>{{count}}</h1>
  <h2>{{double}}</h2>
  <button @click="increase">+1</button>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, toRefs } from 'vue'
interface DataProps {
  count: number
  increase: () => void
  double: number
}

export default defineComponent({
  name: 'Home',
  setup () {
    const data: DataProps = reactive({
      count: 0,
      increase: () => data.count++,
      double: computed(() => data.count * 2)
    })

    return {
      ...toRefs(data)
    }
  }
})
</script>

只有响应式类型,才有响应式特性。

readonly 函数

const original = reactive({ count: 0 })
const copy = readonly(original)
original.count++
copy.count++ // error:Cannot assign to 'count' because it is a read-only property

watch watchEffect

// watch
watch(count, (newValue, oldValue) => {
  console.log(newValue, oldValue)
})

// watch 多个值,返回的也是多个值的数组
watch([double, count], (newValue, oldValue) => {
  console.log(newValue, oldValue)
})

watchEffect(() => {
  console.log(count.value)
})

watchEffect(() => {
  console.log(double.value)
})

相关文章

网友评论

      本文标题:Composition API

      本文链接:https://www.haomeiwen.com/subject/fvrfnktx.html