Detach an item from its parent once it has been added to an array

Currently, I am facing an issue with a form on my blog. The blog is represented as an object that contains multiple content objects within it. I seem to be experiencing some confusion because the reactivity of the content I add to the Array persists with the parent object, even though it's not explicitly defined as a ref.

Below is the Vue Component code:

<script setup lang="ts">

const blog = ref({
    link: 'Link',
    category: 'category',
    title: 'title',
    image: 'Image',
    body: 'Body',
    content: [] as any[]
})

let contentItem = {
    parent: 'parent',
    title: 'title',
    image: 'Image',
    code: 'Code',
    body: 'Body',
}

// Add Content Item
function addContent(content: any) {
    const item = content
    blog.value.content.push(item)
} 

</script>


<template>
<div class="flex p-8 text-slate-600 w-full flex-col gap-4 rounded">
            <h4 class="font-bold text-red-50">Blog Content</h4>
            <input type="text" v-model="contentItem.parent">
            <input type="text" v-model="contentItem.title">
            <input type="text" v-model="contentItem.image">
            <textarea class="w-full h-[200px]" type="text" v-model="contentItem.code"> {{ contentItem.code }} </textarea>
            <textarea class="w-full h-[200px]" type="text" v-model="contentItem.body"> {{ contentItem.body }} </textarea>
            <button class="p-4 w-1/2 bg-slate-50" type="button" @click="addContent(contentItem)">Add Content</button>
        </div>
</template>

`

I have attempted using "readonly" and also tried passing values to another object (as seen in the current code), yet I am still puzzled by why they end up being the same object. I am aware that the solution might be straightforward, but after researching, all I could find were methods to maintain reactivity in an array (which is the opposite of my current problem).

Answer №1

Make sure to pass objects by value rather than by reference:

const { ref, computed, onMounted } = Vue
const app = Vue.createApp({
  setup() {
    const blog = ref({
      link: 'Link',
      category: 'category',
      title: 'title',
      image: 'Image',
      body: 'Body',
      content: []
    })

    let contentItem = ref({
      parent: 'parent',
      title: 'title',
      image: 'Image',
      code: 'Code',
      body: 'Body',
    })

    function addContent(content) {
      blog.value.content.push({...content})
    } 

    return {
      addContent,
      contentItem,
      blog
    }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div class="flex p-8 text-slate-600 w-full flex-col gap-4 rounded">
    <h4 class="font-bold text-red-50">Blog Content</h4>
    <input type="text" v-model="contentItem.parent">
    <input type="text" v-model="contentItem.title">
    <input type="text" v-model="contentItem.image">
    <textarea class="w-full h-[200px]" type="text" v-model="contentItem.code"> {{ contentItem.code }} </textarea>
    <textarea class="w-full h-[200px]" type="text" v-model="contentItem.body"> {{ contentItem.body }} </textarea>
    <button class="p-4 w-1/2 bg-slate-50" type="button" @click="addContent(contentItem)">Add Content</button>
  </div>
  {{blog}}
</div>

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

What is the correct way to align labels to the right in a column layout?

I just started learning React JS and I'm using Material-UI. One issue I encountered is that when I use the column layout with an 'xs' value, the component inside the column appears aligned to the left. To align it to the right, I tried incr ...

Warning: An unhandled promise rejection occurred while using agenda

I encountered an UnhandledPromiseRejectionWarning while running my project which utilizes the agenda package. Here is the code snippet: agenda.define('transferDBField', (job, done) => { if (this.tPrice) { this.prices.push(this.tP ...

Step-by-step guide on correctly plotting the image after converting it to an array using the img_to_array function

I'm trying to figure out how to plot an image that has been converted into an array using keras.preprocessing.image.img_to_array. Here's my approach. To provide a simple example, I downloaded a picture of a duck from the internet: import urllib ...

What is the best way to extract the essential data from the returned value without any unnecessary additions?

Looking for a way to extract specific data from an api response in the format of x[[seconds:cost[[x? I am using php and javascript. How can I separate out the seconds and cost values only? For example, if the response looks like this: x[[16413:2.60[[x I ...

Automatically compile files while performing an npm install or update

I am looking for a way to automatically compile my TypeScript code into JavaScript when another project requires it. For example, when a project runs npm install or updates with my project as a dependency, I want a specific command to be executed after all ...

What is the solution to resolving the error message "Uncaught ReferenceError: Pusher is not defined" in Vue.js 2?

Whenever I try to launch my application, the console shows the following error: Uncaught ReferenceError: Pusher is not defined and Uncaught ReferenceError: App is not defined Despite running the following commands in my terminal: npm install and ...

Convert an array comprising arrays/objects into JSON format

This problem is really challenging for me. The structure of my array goes like this: array1 = [ [array2], [array3], [array4] ... [array17] ] array2 = [ ['obj1'], ['obj2'], ['obj3'] ... ['obj30'] ] ... ... obj1 = ({p ...

Set the Checkbox selections by utilizing the array values in the MUI DataGrid

In my MUI Datagrid, I have 2 columns for ID and City Name. There are only 3 cities represented in the table. Within a citizen object like this: const userMockup = { id: 1, name: "Citizen 1", cities: [1, 2], isAlive: true }; The cities ar ...

Creating a map-like scrolling feature for a full-sized image, allowing both horizontal and vertical movement

My goal is to create an infographic image that can be scrolled horizontally and vertically, zoomed in or out, and where I can add markers just like Google Maps. I attempted the solution of using two scroll views as suggested here: https://github.com/faceb ...

Creating code to ensure a div element is displayed only after a specific duration has elapsed

Can anyone help me with coding to make a div appear on a website after a specific amount of time? Here's an example of what I'm trying to achieve: <div class="container"> <div class="secretpopout"> This is the hidden div that should ...

failure of text to display in d3.append

Having trouble displaying a tooltip on a rectangle in d3js. The tooltip renders, but the text doesn't show up. After researching similar issues, I discovered that I cannot directly append 'text' to a 'rect' element. I tried addin ...

Incorporate the xml2js JavaScript library with Angular 2 for enhanced functionality

I've been attempting to utilize xml2js as an XML parser within my Angular 2 (RC 1 with TypeScript) web application. Unfortunately, I've encountered several errors without finding a solution that works. Here is the detailed process I followed: ...

The v-select menu in Vuetify conceals the text-field input

How can I prevent the menu from covering the input box in Vuetify version 2.3.18? I came across a potential solution here, but it didn't work for me: https://codepen.io/jrast/pen/NwMaZE?editors=1010 I also found an issue on the Vuetify github page t ...

Tips for effectively handling numerous iterations of an identical NPM dependency

Situation I have been working on creating various D3.js charts using the latest version of D3 (4.9.1). However, I also need to incorporate occasional C3.js charts into my application, which poses a challenge as C3 requires D3 v3.5.0. Exploring Options ...

Discover various ways to encapsulate Vue.js components

I am currently in the process of developing a website that utilizes classic multiple pages powered by blade templates. However, I am looking to incorporate vuejs2 components for more dynamic functionalities. Although things are running smoothly, I am faci ...

Issue with React component not updating content after state changes in Next.js framework

Currently, I am facing an issue with my Header component not updating its content on state change. The goal is to show the user's Profile once the state changes, but unfortunately, it does not update immediately; it only changes after a page refresh o ...

In what location can event listeners be found in npm packages?

For a while now, I've been immersed in the world of coding as I work on creating my very own IRC bot using nodejs. This project serves as an invaluable learning experience for me, and as I navigate through the process, I constantly encounter event lis ...

Using a CSS button to activate a JavaScript function: A step-by-step guide

My current project involves writing a script to change the color of text when a specific button is clicked. The idea is that clicking the "Change color1" button triggers the text color change using the following code snippet: <button onclick="myFunction ...

Exploring the world of Next.js version 9.3 and beyond with the exciting addition

As a beginner with Next.js, I am seeking guidance on utilizing getStaticPaths and getStaticProps within catch-all routes. Many blog starters for Next.js 9.3+ focus on single-level blog posts (such as /posts/post-1.md, /posts/post-2.md, etc.), but I am stru ...

Slideshow of table rows in HTML

On a webpage, I am populating an HTML table with a random number of rows ranging from 1 to 100. Regardless of the total number of rows, the requirement is to display only 10 rows at a time on the screen and then shift to the next set of 10 rows every 5 sec ...