[Vue] toRef: convert reactive to ref in order to destructure reactive object used inside template

import {reactive, computed} from "vue"
export default {
  setup() {
    const event = reactive({
        capacity: 4,
        attending: ["Tim", "Bob"],
        spacesLeft: computed(() => {
           return event.capacity - event.attending.length
        })
    })
    
    function increaseCapacity() {
         event.capacity++
    }
      
    return {event, increaseCapacity}
  }
}

In template we will do:

    <p>Spaces Left: {{ event.spacesLeft }} out of {{ event.capacity }}</p>
    <h2>Attending</h2>
    <ul>
      <li v-for="(name, index) in event.attending" :key="index">
       {{ name }}
      </li>
    </ul>
    <button @click="increaseCapacity()">Increase Capacity</button>

I wondered, might there be any way to destructure the event object, so that in the template I don’t always have to write event.?

 

Introducing toRefs

Luckily, there is a way to do this using the toRefs method. This method converts a reactive object to a plain object, where each property is a Reactive Reference pointing to the property on the original object. Here is our completed code using this method:

    import { reactive, computed, toRefs } from "vue";
    export default {
      setup() {
        const event = reactive({
          capacity: 4,
          attending: ["Tim", "Bob", "Joe"],
          spacesLeft: computed(() => {
            return event.capacity - event.attending.length;
          })
        });
        function increaseCapacity() {
          event.capacity++;
        }
        return { ...toRefs(event), increaseCapacity };
      }
    };

Notice that I’m importing toRefs and then using it in my return statement, and then destructuring the object. This works great!

Aside

Before continuing on, I want to mention that if our code didn’t need to also return the increaseCapacity function in the return value, I could have simply written:

    return toRefs(event);

This is because our setup method expects us to return an object, which is exactly what toRefs returns as well.

posted @   Zhentiw  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-11-27 [Typescript] 119. Extreme - Get Readonly Keys
2017-11-27 [Python] Problem with Default Arguments
2017-11-27 [Python] Tuples
2016-11-27 [AngularFire 2] Protect Write Access Using Security Rules
2015-11-27 [Javascript] Array methods in depth - slice
2015-11-27 [ES6] ... spread operator
2015-11-27 [AngularJS] New in Angular 1.5 ng-animate-swap
点击右上角即可分享
微信分享提示