专业的编程技术博客社区

网站首页 > 博客文章 正文

Vue3教程 5.响应式toRef和toRefs函数

baijin 2024-10-04 13:25:25 博客文章 4 ℃ 0 评论

简介

toRef作用:将对象某一个属性,作为引用返回。可能说法比较绕口,我们通过实例来说明这个问题。

需求:我们实现触发事件,在只改动name的情况下,让product.name 和 name 的值都要从 电视机 改变成 空调,我们通过问题来引入toRef的应用场景

问题代码一

<template>
  <h2>product.name:{{ product.name }}</h2>
  <h2>name: {{ name }}</h2>
  <button @click="hello">hello</button>
</template>

<script>
import {reactive} from 'vue';

export default {
  name: 'App',
  setup(){
    let product = reactive({
      name: '电视机',
      sku: [{
        count: 2,
        title: '红色'
      }]
    });
    let name = product.name;
    return {
        product,
        name,
        hello () {
            name = '空调';
        }
    }
  }
}
</script>

我们点击触发hello事件,页面上显示依旧是

点击之前

点击之后

product.name:电视机

product.name:电视机

name:电视机

name:电视机

问题代码二

我们给product.name 加上ref,让它变成响应式,我们改动如下代码


import {reactive, ref} from 'vue';

// setup...
    let name = ref(product.name);
    return {
        product,
        name,
        hello () {
            name.value = '空调';
        }
    }

可以看到如下表格,只有name发生改变

点击之前

点击之后

product.name:电视机

product.name:电视机

name:电视机

name:空调

toRef解决问题


import {reactive, toRef} from 'vue';

// setup...
    let product = reactive({
      name: '电视机',
      sku: [{
        count: 2,
        title: '红色'
      }]
    });
    let name = toRef(product, 'name');
    return {
        product,
        name,
        hello () {
            name.value = '空调';
        }
    }

可以看到如下表格,toRef可以解决这个问题

点击之前

点击之后

product.name:电视机

product.name:空调

name:电视机

name:空调

toRefs使用

toRefs 返回对象中所有属性都响应式,相比之下比toRef写法跟简单,但是肯定会牺牲耗性能,代码如下:

<template>
  <h2>product.name:{{ product.name }}</h2>
  <h2>name:{{ name }}</h2>
  <h2>price:{{ price }}</h2>
  <button @click="hello">hello</button>
</template>

<script>
import {reactive, toRefs} from 'vue';

export default {
  name: 'App',
  setup(){
    let product = reactive({
      name: '电视机',
      price: 2000,
      sku: [{
        count: 2,
        title: '红色'
      }],
    });
    let productObj = toRefs(product);
    let name = productObj.name;
    let price = productObj.price;
    return {
        product,
        name,
        price,
        hello () {
            name.value = '空调';
            price.value = 3000;
        }
    }
  }
}
</script>



Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表