Exploring Vue's reactivity using the composition API and cloning props

In my current component setup, I am receiving props from a parent. However, I am facing an issue where I only want to clone these props without any changes affecting the parent component.

<template>
  <input-text v-model="form.name" />
</template>

export default defineComponent({
  props: {
    record: {
      type: Object,
      required: true,
      default: () => ({}),
    },
  },
  setup(props) {
    const form = ref({})

    // Need to clone props whenever they change
    watchEffect(() => {
      dForm.value = props.record
    })


    return { form }
  },
})

My goal now is to create a duplicate of the incoming props every time they are passed - ensuring that the v-model does not alter the original data in the parent component. How can I successfully clone props.record? Attempting methods like Object.assign({}, props.record) have proven unsuccessful so far.

Answer №1

Check out Deep Watchers

const information = ref({})
watch(
   () => props.data,
   (newValue) => { Object.assign(information.value, newValue) },
   { deep: true } // <- using deep watchers
)

Proceed with Care

Using deep watch involves going through all nested properties in the watched object, which can be resource-intensive for large data structures. Make sure to use it only when necessary and be mindful of the performance impact.

const { createApp, ref, watch } = Vue
 
const Element = {
  props: {
    data: {
      type: Object,
      required: true,
      default: {},
    }
  },
  setup(props) {    
    const info = ref({})
    watch(
      () => props.data,
      (newValue) => { Object.assign(info.value, newValue) },
      { deep: true }
    )
    const updateCounter = () => { info.value.counter++ }
    return { info, updateCounter }
  },
  template: 'Element: props.data: {{data}}<br/> info: {{info}} <button @click="updateCounter">+1</button> <br/>'  
} 
 
const Application = {
  components: {
    Element
  },
  setup() {
    const data = ref({
      counter: 0
    });    
    const increment = () => { data.value.counter++ }
    return { data, increment }
  }
}

const appInstance = createApp(Application)
appInstance.mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
<div id="app" v-cloak>
data: {{data}} <button @click="increment">+1</button> <br/>
<element :data="data"></element><br/>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to handle templates in AngularJS that is reminiscent of Handlebars?

Is there a way to handle an AngularJS template using a syntax similar to Handlebar? <script type="text/ng-template" id="mytemplate"> Name is {{name}} </script> I know how to retrieve the template using $templateCache.get('mytemplate&ap ...

Where can the config file be found in Vue Cli 3.0?

There has been mention of the vue.config.js file in documentation and other sources, as well as previous references to handling configurations in the webpack config file for version 2.0. However, I am unable to locate either file in my project folder tha ...

Hey there, I'm looking to use different CSS fonts on Windows and Mac for the same page on a web application. Can someone please guide me on how to accomplish this?

In order to tailor the font based on the operating system, the following criteria should be followed: For Windows: "Segoe UI" For Mac: "SF Pro" Attempts have been made using the code provided below, but it seems to load before the DOM and lacks persisten ...

Retrieve data using the designated key and convert it into JSON format

If I have the following JSON array: [ {"data": [ {"W":1,"A1":"123"}, {"W":1,"A1":"456"}, {"W":2,"A1":"4578"}, {"W":2,"A1":"2423"}, {"W":2,"A1":"2432"}, {"W":2,"A1":"24324" ...

Javascript function fails to run smoothly during rapidscrolling

I'm facing an issue with my JavaScript code that adjusts the transparency of the navigation bar while scrolling. It works perfectly when scrolling slowly, but when the scrolling speed is fast, it seems like the function is not triggered and the navbar ...

What is the best way to transfer a multidimensional array from PHP to JavaScript?

Attempting to extract array value from a JSON string, I utilize the json_decode function in PHP. <?php $jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php'); $jsonDecoded=json_decode($jsonContent,true); foreach($jsonEncoded[&apo ...

Having trouble with JavaScript's XMLHttpRequest returning an 'undefined' string on the first run of my script. I need to find a way to ensure that it loads correctly during

Before we dive in, a quick disclaimer: My knowledge of JS is limited, and I typically learn on the go when creating scripts. However, my usual method didn't work this time. Currently, I'm working on a small JS script that will function as a book ...

TypeScript Yup schema validation combined with the power of Type Inference

I currently have a unique data structure as shown below: type MyDataType = | { type: "pro"; content: { signedAt: string; expiresOn: string }; } | { type: "default" | "regular"; content: { signed ...

Can you explain the step-by-step process of how an await/async program runs in TypeScript/JavaScript or Python?

As a C++ developer specializing in multithreading, I've been diving into the intricacies of async/await. It's been a challenge for me as these concepts differ from how C++ programs are typically executed. I grasp the concept of Promise objects, ...

Is it possible to use a JQuery function after a page redirect has occurred

Take a look at this interesting fiddle! View the Fiddle I am interested in creating links that scroll to different sections of content areas on my site, similar to the footer links in the example. I have been suggested to use Anglers routing system, but ...

Need help incorporating a "section trail" into your website's navigation sidebar using JS/jquery? Here's how you can do it!

My website is quite extensive and contains numerous elements. There are times when I find myself wanting to navigate back and forth between different sections of the page. I've noticed that some websites have a feature called a "page trail," which di ...

Tips for determining the actions of a node prior to its inception

Is there a way to automatically run scripts on specific elements after their creation? For example, using a jQuery plugin like autoresize to expand the height of a textarea. If I use $('.textarea').autosize(), only the current textareas will be a ...

Leverage webpack to consolidate multiple ES6 classes into a single file for easy importing via a script tag

For the past three days, I've been grappling with webpack in an attempt to complete a simple task that could have easily been done manually. However, I am determined to learn webpack for scalability reasons... I come to you now with a desperate quest ...

What changes will be brought about by switching from createWebHashHistory() to createWebHistory()?

I recently launched an application that utilizes createWebHashHistory() to handle URLs. One example is when a user visits this URL to access the earthquakes channel: https://app.radar.chat/#/channel/earthquakes Now, I am considering transitioning to using ...

Utilizing System.import with Webpack 2 and React for splitting code and managing nested routes

I followed the instructions from a tutorial article on Modus Create titled Code Splitting for React Router with ES6 Imports to create an app. I made some modifications by adding children routes, resulting in the following router configuration: function er ...

Reordering sections in a dynamic manner

I'm working on a single-page website with four sections arranged like this: <section id=“4”> <section id=“3”> <section id=“2”> <section id=“1”> Now, I want to change the order of these sections when scrolling ...

Adding a list without a specific order into a paragraph with the help of jQuery

Working on a client-side class, I am in the process of changing an XHR request and getElementById function to a jQuery ajax request along with jQuery document manipulation. The task at hand is to display descriptions of items available from "Rob's Roc ...

Vue js throws a maximum call stack error when updating a Chart component

I have successfully created a line chart using the Chart.js 3.5 library. The chart is responsive, all animations are working fine too. I am currently facing an issue where I am attempting to update the data from a parent component and trigger a chart updat ...

My table elements are automatically being populated with <tr> elements thanks to Javascript

Upon viewing the screenshot: it is evident that each element is placed within its own tr. My preference is to have each element contained in a td and then wrap everything within a single tr. Here is the updated HTML structure: <div id='result&a ...

Using Vuetify to highlight selected radio buttons in an edit form

One issue I am encountering involves editing a table row. After clicking on the edit button, a form pops up with the data pre-filled for editing purposes. However, the radio button selected previously does not display as checked in the form; both options a ...