Convert a prop into a data attribute using Vue.js 2

I have a basic component being displayed as

<House :_people="[{'name': 'Kevin'}, {'name':'Bert'}, {'name': 'Timmy'}]"></House>

The structure of the component is like this:

<template>
<div class="house">
    <ul>
        <li v-for="person in people">
            {{ person.name }}
        </li>
    </ul>
    <a href="#add" @click="addMark">Add Mark</a>
</div>
</template>

<script>
export default {
    props: ['_people'],
    data: function(){
        return {
            people: this._people
        }
    },
    methods: {
        addMark: function(){
            this.people.push({
                name: 'Mark'
            });
        }
    },
}

The issue arises when I need to pass a JSON payload to the initial component, which sets it as a prop rather than a data attribute. When attempting to manipulate the prop, it does not update. So, I connected the _people prop to the people attribute instead.

Is this approach appropriate? Is there something obvious that I am overlooking?

Answer №1

Send an object as the argument:

friends = {
  collection: [{'name': 'Alice'}, {'name':'Bob'}, {'name': 'Charlie'}]
}

<Home :_friends="friends"></Home>

and after that

arguments: ['_friends'],
functions: {
  addFriend() {
    this._friends.collection.push({
      name: 'Diana'
    })
  }
}

Answer №2

If you want to update an array with a computed property, you can do it in the following way:

export default {
    props: ['_people'],
    data() {
       return {
            added: false
       }
    },
    computed: {
        updatedPeopleList() {
            var copyArray = this._people.slice();

            // Add Mark if 'added' is true
            return this.added ? copyArray : copyArray.push({ name: 'Mark' });
        }
    },
    methods: {
        addMark: function(){
           this.added = true;
        }
    },
}

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

Scrolling horizontally in vue-chartjs-chartwidget

I have a question regarding vue-chartjs. I am looking to achieve a similar result to the one demonstrated in this jsfiddle example: http://jsfiddle.net/mbhavfwm/ Below is the code for my Vue.js component (Chart data is passed through params). &l ...

Creating a Loopback API that seamlessly integrates with Ember.js

Exploring the use of Loopback to create an API that communicates with Ember. Ember expects JSON data to be enclosed in 'keys', such as for an account: { account: { domain: 'domain.com', subdomain: 'test', title: ...

Dealing with adding up optional values from v-model in Vue.js can be a challenging task

Within this function, I need to display the remaining amount. remainingAmount: function() { return parseFloat(this.sumAmount) - (parseFloat(this.cash) + parseFloat(this.kNet) + parseFloat(this.kNetOnline)); } The three parameters cash ...

The loading animation does not appear in the NextJS 14 - loading.tsx component while a GET request is being processed

Component with 500 photos displayed on my page: 'use client'; import { useEffect, useState } from 'react'; import { wait } from '@/components/loaders/skeletons'; export default function Postings() { const [photos, setPhotos ...

Placing a Div wrapper around the contents of two corresponding elements

I am currently attempting to wrap a div with the class name 'wrapped' around two other divs containing innerHTML of 'one' and 'two'. <div class='blk'>one</div> <div class='blk'>two</di ...

Utilizing the onscroll feature to trigger a function within a ScrollView

I am facing an issue with an animated view where I need to execute multiple events within the onScroll property. The current onScroll implementation is as follows: onScroll={ Animated.event( [{ nativeEvent: { conten ...

Difficulty with deploying Next.js to Vercel due to restrictions on rate limits when utilizing getStaticProps()

In my Next.js project connected to Apollo, I have around 50 static URLs fetching data using getStaticProps(). The performance is great, and I enjoy how the pages load. However, a problem arises when Vercel builds the static versions of these pages during d ...

Can a webpage be sent to a particular Chromecast device without using the extension through programming?

My organization has strategically placed multiple Chromecasts across our facility, each dedicated to displaying a different webpage based on its location. Within my database, I maintain a record of the Chromecast names and their corresponding URLs. These d ...

Changing text on a button with JavaScript toggle functionality: A step-by-step guide

I am looking to implement a feature where I can hide and show overflow content in a div. When I click on the expand button, it expands the content. However, I want this button to toggle and change text as well. Thank you! function descriptionHeightMo ...

Using the highcharts-ng library in combination with ng-repeat was successful in creating multiple charts. However, in order to display different data for each chart, the

I need to provide the date either from the view template or possibly from the controller in order for the highchart to display the data specified by the <highchart /> directive. Explanation : <ul> <li ng-repeat="li in list"> ...

What is the approach of Angular 2 in managing attributes formatted in camelCase?

Recently, I've been dedicating my time to a personal project centered around web components. In this endeavor, I have been exploring the development of my own data binding library. Progress has been made in creating key functionalities akin to those f ...

Transition from FadeOut to loading content and displaying it

Is there a way to simply display the content after loading without using fadeIn? $(function() { $('.hovers').click(function(event) { var target = $(this).attr('href'); window.location.hash = target; $.ajax({ url: ...

Determining if a user is already logged in from a different device using express-session

After a user logs in, I assign the username to their session with the code: req.session.username = "...."; This identifies the session with a username, but now I need to figure out how to detect if this same username is already logged in from another dev ...

AngularJS radio buttons can now be selected as multiple options

Currently, I am in the process of learning angular and have implemented a radio button feature in my program. However, I have encountered a perplexing issue that I cannot seem to explain. <!DOCTYPE html> <html> <head> <meta ch ...

Deleting an element from a reference array in Mongoose

In my code, I have a User model that contains an array of references to other users: friends : [ { type: Schema.Types.ObjectId, ref: 'User' } ] I am currently struggling with removing an item from this list. Here is what I have attempt ...

Animating CSS styles in Vue.js based on JavaScript triggers

Within my Vue.js application, I've implemented a login form that I'd like to shake whenever a login attempt fails. Though I have achieved the desired shaking effect, I'm not completely satisfied with my current solution. Here's a simpl ...

Choose carefully when to utilize forkJoin

In a particular scenario, I need an application to generate menus based on specific contexts. Here are the definitions for menuA and menuB: // menuA example from a given source menuA() { return [ { a: 'demo1', b: &apo ...

Unlock the Power of Vue Draggable in Vue.js 3 with These Simple Steps

When attempting to implement Draggable in Vue.js 3, I encountered an error message: VueCompilerError: v-slot can only be used on components or <template> tags. Below is a snippet of my code: <draggable tag="transiton-group" name="s ...

Sending data from jQuery to an AngularJS function is a common task that can be accomplished in

In my Controller, I have a function that saves the ID of an SVG path into an array when a specific part of the image.svg is clicked. $(document).ready(function(){ var arrayCuerpo=[]; $('.SaveBody').on("click", function() { ...

Spread the picture on social media using Progressive Web App

I am currently working on a Nuxt PWA where I have implemented a function to convert HTML to Canvas using a specific package. The output generated is in base 64 format. My goal now is to find a way to easily share this image through various platforms such a ...