search

Home  >  Q&A  >  body text

How to skip deeply nested properties in Vue's Composition API for reactive conversion?

In vue-composition-api: Using the reactive() method, I want to keep a part of the object as a reference.


I have some products, belonging to custom categories:

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

and the order list referencing the products in the deep object:

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

I checked that these are different objects by example.orders[0].product == chair -> false. I also discovered that example.orders[0].product is not of type Product.

Since I can have many different orders, and the products contain a lot of data, I want example.orders[].product to retain a reference to the original product.

I don't need the reactivity of the products themselves because they are constant. (This is an Electron application, the content will remain unchanged as long as the program is running)

I just want to react to the order.

P粉044526217P粉044526217241 days ago361

reply all(1)I'll reply

  • P粉340264283

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

    Use 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)
      }))
    });

    NOTE: Please read the warnings on the label.

    reply
    0
  • Cancelreply