首页  >  问答  >  正文

如何在Vue的Composition API中跳过深层嵌套的属性进行响应式转换?

在 vue-composition-api 中: 使用reactive()方法,我想保留对象的一部分作为引用。


我有一些产品,属于自定义类别:

const chair = new Product(...); // lots of information in each product 
const table = new Product(...); // lots of information in each product

以及在深层对象中引用产品的订单列表:

let example = reactive({   
  orders: [
    { product: chair, quantity: 2 }, 
    { product: table, quantity: 1 }, 
    { product: chair, quantity: 6 }, 
    { product: table, quantity: 2 },
  ] 
});

我通过 example.orders[0].product == chair -> false 检查发现这些是不同的对象。 我还发现 example.orders[0].product 不是 Product 类型。

由于我可以有很多不同的订单,并且产品包含很多数据,因此我希望 example.orders[].product 保留对原始产品的引用。

我不需要产品本身的反应性,因为它们是恒定的。 (这是一个电子应用程序,只要程序运行,内容就会保持不变)

我只想对订单进行反应。

P粉044526217P粉044526217206 天前330

全部回复(1)我来回复

  • P粉340264283

    P粉3402642832024-03-27 12:41:59

    使用markRaw

    import { markRaw, reactive } from 'vue';
    
    const example = reactive({   
      orders: [
        { product: chair, quantity: 2 }, 
        { product: table, quantity: 1 }, 
        { product: chair, quantity: 6 }, 
        { product: table, quantity: 2 },
      ].map(el => ({ 
        ...el,
        product: markRaw(el.product)
      }))
    });

    注意:请阅读标签上的警告。

    回复
    0
  • 取消回复