Vue3:组合API-toRef函数

250 阅读1分钟

 写在前面

        朋友们晚上好呀,今天用到了toRef函数,那么今天就简单讲下吧。

定义响应式数据:

        toRef是函数,转换响应式对象中某个属性为单独响应式数据,并且值是关联的。

示例代码:

<template>
  <div>
    <div>数据的响应式</div>
    <hr>
    <!-- <div>{{obj.msg}}</div> -->
    <div>{{msg}}</div>
    <div>{{info}}</div>
    <div>
      <button @click='handleClick'>点击</button>
    </div>
  </div>
</template>

<script>
import { reactive, toRef } from 'vue'

export default {
  name: 'App',
  setup () {
    // 需求:模板中必须有添加对象obj前缀,而是直接获取属性
    // reactive方法包裹的对象中的数据都是响应式的
    const obj = reactive({
      msg: 'hello',
      info: 'hi'
    })
    // 把对象中的单个属性取出并且保证数据的响应式
    const msg = toRef(obj, 'msg')
    const info = toRef(obj, 'info')
    const handleClick = () => {
      obj.msg = 'nihao'
      obj.info = 'coniqiwa'
    }
    // reactive中的对象属性如果重新赋值会失去响应式能力
    return { msg, info, handleClick }
  }
}
</script>

<style lang="less">
</style>

写在最后

        toRef方法可以把对象中的单个属性取出并且保证响应式能力~

        今天就到这儿吧,下期见呀վ'ᴗ' ի~