Proper method for updating a component prop in Vue.js from within its method

Here is the code snippet for a Vue.js component:

var list = Vue.component('list', {
  props: ['items', 'headertext', 'placeholder'],
  template: `
    <div class="col s6">
      <div class="search">
        <searchbox v-bind:placeholder=placeholder></searchbox>

        <ul class="collection with-header search-results">
          <li class="collection-header"><p>{{ headertext }}</p></li>
          <collection-item
            v-for="item in items"
            v-bind:texto="item.nome"
            v-bind:link="item.link"
            v-bind:key="item.id"
          >
          </collection-item>
        </ul>
      </div>
    </div>`,

  methods: {
    atualizaBibliografiasUsandoHipotese: function (value) {
      var query = gql`query {
        allHipotese(nome: "${value}") {
          id
          nome
          bibliografiasDestaque {
            id
            nome
            link
            descricao
          }
        }
      }`;
      client.query({ query }).then(function(results) {
        this.items = results['data']['allHipotese'][0]['bibliografiasDestaque'];
      }.bind(this));
    },
  }

});

When I call the

atualizaBibliografiasUsandoHipotese
method from another javascript file to update the component, I encounter a warning message from Vue:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "items"

I have tried several solutions to resolve this warning without success. Can someone assist me in fixing this issue? Thank you

Answer №1

If you want to avoid mutating props, here is an alternative approach:

var list = Vue.component('list', {
    props: ['items', 'headertext', 'placeholder'],
    template: `
      <div class="col s6">
        <div class="search">
          <searchbox v-bind:placeholder=placeholder></searchbox>
          <ul class="collection with-header search-results">
            <li class="collection-header"><p>{{ headertext }}</p></li>
            <collection-item 
              v-for="item in myItems"
              v-bind:texto="item.nome"
              v-bind:link="item.link"
              v-bind:key="item.id"
            >
            </collection-item>
          </ul>
        </div>
      </div>`,

    data: ()=> { return { 
            myItems: this.items
        }
    },

    methods: {
        atualizaBibliografiasUsandoHipotese: function (value) {
            // Your Code
            this.myItems = results['data']['allHipotese'][0]['bibliografiasDestaque'];
        }.bind(this));
    },
});

It's worth noting that the v-for loop now iterates over items in myItems.

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

Struggling to capture an error generated by Sequelize within a universal Middleware block

In a test project, I have successfully implemented CLS transaction control in Sequelize using 'cls-hooked'. The transactions work seamlessly both in the command line and with Express. They are injected and managed automatically, rolling back on a ...

Unable to retrieve JSON data in servlet

I am having trouble passing variables through JSON from JSP to a servlet using an ajax call. Despite my efforts, I am receiving null values on the servlet side. Can someone please assist me in identifying where I may have gone wrong or what I might have ov ...

What is the advantage of parsing values in a switch statement compared to an if condition?

function checkInput() { let value = document.getElementById('test').value; if (value == 1) { console.log("It works with if statement"); } } function checkSwitch() { let value = document.getElementById('test').value; switc ...

jQuery functions failing to target dynamically generated elements

I've encountered an issue while attempting to implement my jQuery functions on dynamically created content using the .on API from jQuery. The main objective of the code is to display a specific set of options only when a user hovers over the ".feed_po ...

A useful tip for adding a blank line in a specific index of an array is to utilize the character while iterating through the array with a v-for loop to generate a list

I am trying to find a way to add an empty line before a specific array element while iterating through it using v-for to generate a list. Using \n does not seem to be effective for this task. <!-- Here is the template section --> <ul> ...

Leveraging RXJS for efficient data retrieval in nodejs

When dealing with sending a bulk of data and moving on to the next one upon completion, it can be quite challenging. Take for instance this function: async function test() { await sample.sampleStructure() await sample.sampleDataAdd() await sample.sa ...

Validation for prototype malfunctioning

I am currently using Prototype.js to implement form validation on my website. One of the fields requires an ajax request to a PHP file for validation purposes. The PHP file will return '1' if the value is valid and '0' if it is not. Des ...

Converting RSS title to HTML format with the help of JavaScript

I am currently working on populating a menu on a webpage with the 5 latest topics from our site's RSS newsfeed using JavaScript (specifically jQuery version 1.9.1). I have been searching for a solution, but most answers I find reference deprecated scr ...

Error detected at /register/ Invalid Fernet key format - it should be 32 bytes in length and encoded in url-safe base

I'm currently working on encoding the payload data from a form I've made using React on the frontend. Here's the code snippet I am using: const handleSubmit = (e) => { e.preventDefault(); const encryptedPassword = CryptoJS.AES.en ...

Retrieving data from a JSON using Typescript and Angular 2

Here is an example of what my JSON data structure looks like: { "reportSections": [ { "name": "...", "display": true, "nav": false, "reportGroups": { "reports": [ { "name": "...", "ur ...

Executing certain test suites with defined capabilities in Protractor

My website is designed to be compatible with both desktop and mobile browsers, each having its own unique user interface. In my protractor config file, I have some suites that need to be tested using the desktop user agent, while others require testing usi ...

execute function when loading a page on nuxt framework

Can Nuxt middleware be modified to execute after a page has been mounted? If the following middleware is used: export default function ({ app }) { if (!process.server) { app.$somePluginFunction() } } It currently triggers when navigating to a pag ...

Following the submission of a POST request, an error occurred stating: "Unable to assign headers once they have been sent to

I'm having trouble figuring out what's wrong with my code. Whenever I send a post request, I get an error message saying "Cannot set headers after they are sent to the client". My model includes a comment schema with fields for user, content, and ...

Combining a JavaScript NPM project with Spring Boot Integration

Recently, I built a frontend application in React.js using NPM and utilized IntelliJ IDEA as my IDE for development. Additionally, I have set up a backend system using Spring Boot, which was also developed in IntelliJ IDEA separately. My current goal is t ...

What is the best way to send a string from an HTML form, route it through a router, and create and save an object?

Currently, I am facing an issue while attempting to transfer a string from the frontend to the backend. The technologies I am using include Node, Express, Body Parser, EJS, and PostgreSQL. Here is the basic structure of my file system: – app |– api ...

Issue with closing Bootstrap 5 alert in Vue component

I'm currently tackling a Vue project and I'm stumped as to why this alert isn't closing. Initially, I had the commented-out section working fine, but when I replaced it with code from the Bootstrap website, the issue persisted. <template& ...

Jquery Deferred failing to activate done or when functions

I'm currently working with 2 ajax calls that I'm connecting using $.when in order to execute certain tasks once they are completed. Below is the code snippet: function ajaxCall(url, targetDiv) { dfd = new $.Deferred(); $.ajax({ ...

vue form is returning empty objects rather than the actual input data

I am attempting to transfer data from my component to a view in order for the view to save the data in a JSON file. I have verified that the view is functioning correctly as I attempted to log the data in the component and found it to be empty, and the r ...

jQuery validation does not work properly when using .element(element) in a custom method

I am struggling with a custom rule that is supposed to check dependencies by validating other inputs it relies on. However, when I implement this validation, it seems like all other validations are being ignored. Here is my custom validation rule: jQuery ...

Does JavaScript automatically round large numbers?

I have a simple array: myArray = [{"egn":79090114464},{"egn":92122244001},{"egn":10005870397643185154},{"egn":10000330397652279629},{"egn":10000330397652279660},] However, when I append the values from thi ...