In Vue, props are not automatically assigned; be sure to avoid directly mutating a prop when assigning it manually to prevent errors

I am working with two Vue components: GetAnimal.vue and DisplayAnimal.vue. GetAnimal.vue sends a JSON object containing animal data to DisplayAnimal.vue using router push. DisplayAnimal.vue then displays this data. The process flow is as follows: I navigate to /getanimal, click on a button that triggers the getAnimal() function, which redirects me to /viewanimal (via router push):

GetAnimal.vue:

<script>
    import axios from 'axios';

    export default {
        data: function () {
            return {
                name: 'defaultAnimal',
                defaultanimal: {
                    name: 'Cat',
                    furColor: 'red',
                    population: '10000',
                    isExtinct: false,
                    isDomesticated: true
                },
                animal: String
            }
        },
        methods: {
            getAnimal: function () {
                console.log("this.defaultanimal: " +
                    JSON.stringify(this.defaultanimal));

                this.$router.push({
                     name: "viewanimal",
                    params: {
                         animal: this.defaultanimal
                     }
                 });

            },
...

DisplayAnimal.vue:

<template>
    <div>
        <h1>Displaying animal:</h1>
        <p>Animal name: {{animal.name}}}</p>
        <p>Fur color: {{animal.furColor}}</p>
        <p>Population: {{animal.population}}</p>
        <p>Is extinct: {{animal.isExtinct}}</p>
        <p>Is domesticated: {{animal.isDomesticated}}</p>

    </div>
</template>

<script>
    import axios from "axios";

    export default {
        props:  {
            animal:  {
                name: {
                    type: String
                },
                furColor:  {
                    type: String
                },
                population: String,
                isExtinct: String,
                isDomesticated: String
            }
        },

        name: "DisplayAnimal",

        methods: {

        },
        created() {
            console.log("animal param: " +
                JSON.stringify(this.$route.params.animal));
            this.animal = this.$route.params.animal;
        }
    };
</script>

The animal data gets displayed properly:

https://i.sstatic.net/dQJHe.png

However, there seems to be a warning in the console:

https://i.sstatic.net/YhAuP.png

The line that assigns the props explicitly, this.animal = this.$route.params.animal;, could be causing the warning.

Yet, if I remove that line, the animal data does not display at all:

https://i.sstatic.net/0ne0O.png

In my router.js file:

{
    path: "/viewanimal",
    name: "viewanimal",
    component: () => import('./views/DisplayAnimal.vue'),
    props: {animal: true}
},
{
    path: "/getanimal",
    name: "getanimal",
    component: () => import('./views/GetAnimal.vue')
}

I had set props: {animal: true} thinking it would auto assign, but that doesn't seem to be happening. How can I resolve this?

Answer №1

It's a common mistake to directly update props

Furthermore, it is not logical to have the animal prop in the DisplayAnimal component if it is not passed from its parent component. The animal should be declared within the component's data so that you can update it in the created callback.

For example:

data() {
  return {
    loading: true, // You might want to display a loader while fetching data
    animal: {
        id: -1,
        name: '',
        furColor: '',
        population: 0,
        isExtinct: false,
        isDomesticated: false
    }
  }
},
created() {
  this.animal = this.$route.params.animal;
  this.loading = false;
}

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

Troubleshooting Problems with POST Requests in ExpressJS

Currently, I am working on developing a feature in NodeJS that allows users to upload files. However, I am encountering difficulties while attempting to make a simple POST request. In my index.ejs file, I have written code that generates a form and initia ...

Stop dropdown from closing when clicking outside of it

Is there a way to prevent a CDropdown from closing automatically when I click outside of it? I need this functionality so that I can copy text from somewhere and paste it into the CInput field inside the dropdown. Any suggestions on how to achieve this w ...

Choosing the right jQuery selector to target a section that contains div elements

Whenever the h2 element within a section is clicked, I want all the fields in that section to be displayed. For example, if the user clicks on 'Contact Information', the three form inputs (fields) below the Contact Information heading should appe ...

The elements within the array are being refreshed accurately, however, a separate component is being removed

I have developed a component that has the ability to contain multiple Value components. Users can add as many values as they want, with the first value being mandatory and non-removable. When adding two new Value components, I provide input fields for name ...

Migrating to Angular Universal for server-side rendering with an external API server

Thank you for taking the time to read my query. I have developed a project using server-side Node.js and client-side Angular 6. The purpose of the app is to provide information on cryptocurrency prices and details. I am now looking to transition my Angu ...

React Tour displays incorrect positions when coupled with Slide transitions in Material UI Dialog

Currently, I am utilizing the react-tour library to incorporate a guidance feature into my project. The issue arises in the initial step which involves a small component within a <Dialog /> that requires highlighting. However, due to a transition ef ...

Unable to retrieve information from the json-server

For my current project in Backbone.js, I'm utilizing the json-server package to populate it with data. I've created a db.json file containing the data and executed the command json-server --watch db.json. The server started successfully and is ru ...

Using `await` is only permitted in an asynchronous function within Node.js

I've been working with node and express to develop a server for my application. Here is a snippet of my code: async function _prepareDetails(activityId, dealId) { var offerInfo; var details = []; client.connect(function(err) { assert.equ ...

Determining the visibility of an element on a webpage using JavaScript and Puppeteer

I've created a framework that scans websites hosted on our servers to ensure they comply with our policies. If any prohibited content is found, we capture a screenshot along with other relevant details. However, taking a screenshot may not be possibl ...

Steps for automatically closing a TextPrompt if the end user does not respond within a specific time frame

How can I programmatically close a Prompt in Microsoft Chatbot SDK v4, such as TextPrompt or ConfirmPrompt, and end the dialog after a certain period of time if the user does not reply? I attempted to use setTimeout and step.endDialog but encountered issu ...

Sign up for your own personalized Express and HBS helper now!

As a newcomer to Node, I appreciate your patience with me. I recently utilized the express generator module with the -hbs flag to switch from the default templating engine to Handlebars. Currently, I am attempting to register a custom helper to enable me ...

I am facing an issue with effectively passing properties from a parent state to its child component

In the Login component, I set the authentication state using the token as false initially. After a successful login, the token is changed to true. function Login() { const [user, setUser] = useState({ name: '', email: '' }); const [ ...

Is there a way to prevent advertisements from appearing in npm?

As I execute various npm commands, my console gets bombarded with ads promoting different projects and individuals. While I enjoy contributing to open source projects, I believe the console output of a tool should not be used for advertising. Thank you fo ...

I'm encountering an issue where Bulma is taking precedence over the CSS of my Vue3

In my Vue CLI 3 project, I'm utilizing Bulma and have included the import in the 'index.js' file like so: import { createApp } from 'vue' import App from './App.vue' import router from './router' require('@ ...

Utilize AngularJS's OrderBy feature to iterate through the list for navigation in ascending order by Index

I am looking to customize the order of an Object-array using ng-repeat based on their index keys in ascending order. $scope.paneContainer = {books:[{}] } ; $scope.paneContainer.books[0].science = { title:"science", content:"web/app/views/partials/scienc ...

Develop a line using botbuilder

Good day. I'm currently working on a vue js component that will function as a botbuilder. The main goal is to manipulate the cards displayed on the screen and establish links between them to define the flow of actions. Here's an image for referen ...

Retrieving Information with the Fetch API in Node.js and Storing it in a MongoDB Database

I'm a newcomer to mongooseDB and am currently experimenting with inserting data from an API into the database. It successfully creates the Collection, but unfortunately it is not generating the documents. Any suggestions on what I might be doing incor ...

testing express router with several different handlers

I have been testing my guard middleware and everything appears to be functioning correctly, but my expect statement is failing. /// auth.test.js const request = require('supertest'); const express = require('express'); const app = req ...

The type '{}' is lacking the 'submitAction' property, which is necessary according to its type requirements

I'm currently diving into the world of redux forms and typescript, but I've encountered an intriguing error that's been challenging for me to resolve. The specific error message reads as follows: Property 'submitAction' is missing ...

Which option is the speediest: using script setup or the setup function?

When working with Vue3, which method is more efficient in terms of speed: <script setup></script> <!-- Option 1 --> <script>setup() return {}</script> <!-- Option 2 --> ...