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

The transparency level of materials in THREE.js

When using the lambert shader, I encountered an issue with setting the material. In the example provided, it sets the material as follows: this.material.uniforms.emissive.value = new THREE.Color( Math.random(), Math.random(), Math.random()); Prior ...

Tips for refreshing extensive JSON structures?

I receive product data from the server in JSON format, containing properties and nested arrays up to 4 levels deep. In the frontend, users can update values within these nested structures. Should I keep track of the path and reconstruct the entire JSON obj ...

Visual Studio cannot find the reference for require, resulting in an error in Node.js

I'm currently working on developing a web application using Visual Studio, Node.js, and React.js var fs = require('fs'); var path = require('path'); var express = require('express'); Unfortunately, I encountered an erro ...

The date format adjustments vary depending on the web browser being used

I have a JavaScript function that displays the date in the browser, but the format changes depending on the browser. For example, when I open my project in Chrome, the format is 4/30/2015, but when I open it in IE, it's displayed as 30 April, 2015. Ho ...

Best practices for handling errors beyond network problems when using the fetch() function

I am facing a situation where the route of my fetch() call can result in two different responses, each requiring a different action. However, I have noticed that the catch() method only handles network errors as far as I know. Currently, my code looks lik ...

Angular JS: Saving information with a promise

One dilemma I am facing is figuring out where to store data that needs to be accessed in the final callbacks for an http request. In jQuery, I could easily handle this by doing the following: var token = $.get('/some-url', {}, someCallback); tok ...

Having the same name for multiple query parameters does not result in an array being returned

Using the link http://example.com/users?test=1&test=2 router.route('/users/?').get((req, res) => { console.dir(req.query) //=> { test : 1 } }) The output is { test : 1 } instead of an expected array [ 1, 2 ]. Even ?test[]=1&test ...

Understanding the mechanics of utilizing node modules and requiring them within an Express 4 router

After initiating a node project using an express 4 generator, I have set up the following routing code in the /routes/index.js file: // ./routes/index.js var express = require('express'); var router = express.Router(); router.get('/' ...

Can the installation of Canvas be done on a device with the M1 chip?

When attempting to install canvas on a MacBook Pro M1 using the command: npm install --save-dev canvas An error is displayed: npm ERR! code 1 npm ERR! path /Users/xiaoqiangjiang/source/reddwarf/frontend/js-wheel/node_modules/canvas ... (error message con ...

"Is it possible to include a button for horizontal scrolling in the table

I have a bootstrap table with overflowing set to auto within its container, along with a locked first column. While a horizontal scroll bar allows for viewing additional data, I am looking to incorporate buttons for navigation as well. Users should have th ...

Paste the current webpage's URL into a fresh alert popup using javascript"

I found myself spending hours trying to figure out the best way to create a JavaScript function that would copy the current URL and display it in a new alert window. Imagine a scenario where a user clicks on "Share this page" and a new alert window pops u ...

Creating a series of image files from CSS and Javascript animations using Selenium in Python

Looking to convert custom CSS3/Javascript animations into PNG files on the server side and then combine them into a single video file? I found an interesting solution using PhantomJS here. As I am not very familiar with Selenium, adapting it for use with S ...

Having trouble deciphering this snippet of Express JS source code

Upon reviewing the Express JS source code, I came across the main module where express is being exported. module.exports = createApplication; function createApplication() { var app = function(req, res, next) { app.handle(req, res, next); }; m ...

Angular2: Issue encountered while processing click event

When I click a button on my client application, it sends a request to the server I created using Express. The request handler in the server simply logs 'Delete from server' every time the button is clicked. I am encountering these errors when cl ...

Creating a modal using JavaScript and CSS

When I click on the hello (plane geometry) as shown in the figure, a popup appears on the extreme left of the screen instead of appearing on the plane geometry box. Can someone please help me fix this issue? I have also included the code below: https://i. ...

Enlarging a JSON structure exported from Clara.IO using Three.js

As a beginner in Three.JS, I have been honing my skills in creating scenes and models. Recently, I imported a washing machine model into my scene and positioned it accordingly. Now, I am trying to scale it up to make it larger, but I am unsure of how to do ...

What is the reason objects cannot be compared in JavaScript?

I have a straightforward code snippet here. Its purpose is to authenticate the user against the author of the post and grant the authenticated user access to edit the post. exports.edit = function(req, res){ Post.findById(req.params.post_id, function ...

Trouble with exporting and importing an Express application

Starting with a simple Express example of 'Hello World', I am looking to refactor the code into separate files for configuration and routing. var express = require('express'); var app = express(); app.get('/', function (req, ...

Can you iterate through two arrays to find common values?

Upon examining my firebase database, I found the following structure: Users { askdfasdf: John: { Selection: [1,2,3] }, fasfadffe: Mark: { Selection: [1,2,4] } } Players { { name: &apos ...

Filter through the array using the cast method

Trying to implement this: let selections = list.filter(obj => obj.type === "myType"); An issue arises with the filter function displaying an error message which states 'filter' does not exist on type 'NodeType' I attempted to ...