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 holding Firestore back from advancing while Firebase Realtime Database continues to evolve?

I am currently working on a chat application using Firebase within my Vue.js project. In this setup, I need to display the user's status as either active or inactive. To achieve this, I implemented the solution provided by Firebase at https://firebase ...

Why isn't the correct component being shown by react-router?

I have encountered an issue with my code. When I type localhost:8080 in the browser, it displays the App.js component as expected. However, upon navigating to localhost:8080/#/hello, it still shows the App.js component instead of hello.js. Interestingly, ...

Enhance CSS delivery for the items listed below

Reduce the delay caused by rendering JavaScript and CSS above-the-fold. There are 16 CSS resources currently blocking the rendering of your page. This delay could be affecting the loading time of your content. To improve this issue, consider deferring or ...

Send various pieces of information using Jquery/Ajax

I have encountered a challenge with my script - it currently only sends one value to the requested URL, but I now need it to handle two values. Unfortunately, I haven't been able to figure out how to do this. Each checkbox on the page is paired with ...

What is the best way to combine a collection of strings and HTML elements in a React application?

I am facing a challenge with my list of names. I typically use .join to add commas between each name, but one specific item in the list needs to display an icon of a star next to it based on a certain condition. The issue is that using join turns everyth ...

Is it feasible to exclude certain CSS files in an HTML Master page within the .NET framework?

On my website, I have 6 CSS files linked, but on a specific page, I only need to use 3 of them. Our developers are using a master page in .NET and are hesitant to make changes to it. Therefore, I am wondering if there is a way to exclude certain linked C ...

What is the best way to display images one by one from a map using a random fade effect?

I am in the process of creating a logo wall for a website. I successfully managed to display them randomly using a map, but now I want to make them appear one by one in a random order (for example: image 1, image 6, image 3, ...) and keep them visible once ...

The performance of my Angular app is top-notch, but I'm having some trouble with ng

Issues with Loading Controllers in My App After deploying and running my app in a browser, I encountered an issue with loading controllers. While I can reach all the controllers/services successfully, one particular controller is not loading properly. To ...

Having trouble retrieving the $scope value in HTML, even though it was assigned within the success function of $http.post

Having trouble accessing the values of $scope properties after a successful $http post in index.html file. Here is the code snippet for reference, any help in resolving this issue would be greatly appreciated as I am new to AngularJs var app = angular.m ...

Text alignment issue in Material UI Data Grid Component

Currently, I am working with a DataGrid component nested inside a div that is enclosed within a Box component. I am facing issues in centering the content of the DataGrid and styling the header text. The code snippet I'm using is: Blockquote <B ...

What is the purpose of the `Bitwise operator |` in the `d3.shuffle` source code and how can it be understood

Learning about the Bitwise operator | can be found in the document here and a helpful video tutorial here. However, understanding the purpose and significance of | may not come easily through basic examples in those resources. In my exploration of the sou ...

Exploring the handling of the nth element within a jQuery each loop

In the process of looping through elements using an each loop, function test(){ $('#first li').each(function(n){$(this).//jQuery effects for nth li of first \\ need to process nth li of id="second" simultaneously }); Is there a wa ...

Guide to animating the height of a div using jQuery:

I'm hoping to create a cool animation effect where a certain part of a div expands to 100% width when clicked, and then reverts back to its original height on a second click. I've tried writing some code for this, but it's not working as exp ...

What is the significance of [Function: bound ] in the context of node debugging?

So I was trying to debug my .js file using node debug and when I used catch(error) { It only displayed [Function: bound ] when I tried console.dir(error) What is causing this issue? How can I access the full error object? And how do I retrieve the stack ...

How do I retrieve a nested object element based on the value of a specific field in Mongoose?

Below is the teamModelSchema schema that I am working with. var teamMemberModelSchema = new mongoose.Schema({ "email": { "type": String, "required": true, "min": 5, "max": 20 }, "name": { "type": String ...

Attempting to enable a checkbox using a controller located in a separate controller

I am attempting to trigger a checkbox from a separate controller. Suppose I have a card called information technology under one controller, and when clicked, it should redirect to another page that contains a checkbox for information technology managed by ...

sort response data based on date in vue

Is there a way to sort response data by date in vue2? Specifically, how can we filter the data by month, year, or week when a corresponding button is clicked? Here's an example of the response data I received: [ { "date": "2017-02-05", "views": 1, "r ...

Issues with Javascript positioning in Chrome and Safari are causing some functionality to malfunction

My Javascript script is designed to keep an image centered in the window even when the window is smaller than the image. It achieves this by adjusting the left offset of the image so that its center aligns with the center of the screen. If the window is la ...

Unable to resolve the issue of Duplicate keys detected with value '0'. This could potentially lead to errors during updates

Encountered a warning in Vue js stating 'Duplicate keys detected: '0'. This warning could potentially lead to an update error. To resolve this issue, I utilized the getter and setter in the computed variable and dispatched the value to Vuex ...

Dominate with asyncCommand and Ajax in MVC ActionResults

I am currently diving into front-end development and working on a project that involves fixing bugs. Right now, I am utilizing Knockout/MVC ActionResults. One of my tasks is to modify a form so that it cannot be submitted with a double click. I initially ...