Store information from a function in Vue.js

Trying to set data from a method involves using fetch to retrieve REST data. However, attempting to set the data with this.item = 'test' does not seem to work. The issue arises when trying to access this.item inside ".then" as it doesn't work properly. Strangely, it works fine outside of the ".then" block. It's crucial to use the REST call to fetch the necessary data.


        Vue.component('internal_menu', {
            props: ['list'],
            data: function () {
                return {
                    item: '1'
                }
            },
            methods: {
                teste(event)
                {
                    event.preventDefault();
                    var payload = {
                        method: 'GET',
                        headers: { "Accept": "application/json; odata=verbose" },
                        credentials: 'same-origin'    // or credentials: 'include'
                    }
                    const url = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('"+ this.list +"')/Items?$select=Title,Id,Link,Icone&$orderby=Title%20asc";
                    fetch(url,payload)
                        .then((resp) => resp.json())
                        .then(function(data) 
                        {
                            let items = data.d.results;
                            this.item = 'teste';// this won't work here
                        })
                        .catch(function(error) {
                            console.log(JSON.stringify(error));
                        });
                    this.item = 'tst123'; //this will work here
                },

            },
            template: `
                <div id='tst'>
                    <h3>{{list}} - {{item}}</h3>
                    <button v-on:click="teste">Try Me</button>
                </div>
            `,
            mounted: function () {
                this.getMenuData();
            }
        })

        new Vue({
            el: "#app"
        })
    

Thank you, Everton

Answer №1

Have you ever encountered this scenario?

.then(function(data) 
      {
          let items = data.d.results;
          this.item = 'example';// not functional in this case
      })

The issue arises because your closure's reference to this is limited to the scope of the anonymous function. To resolve this, it is recommended to utilize the fat arrow function as it allows for proper context retention within the Component.

.then((data) => {
    let items = data.d.results;
    this.item = 'example';
})

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

Error arises on Github when submitting a pull request due to a conflicted package

When facing conflicts in the package.json file while submitting a pull request, what is the best approach to resolve them? I usually attempt using git pull origin, but it tends to generate numerous merge commits. ...

HTML is being incorrectly rendered by the Express framework

Looking to Use HTML as View Engine in Express? After going through the link, I attempted to start my server with an index.html file on port 8001. However, it failed to render correctly and showed an error in the console: Server Started Error: SyntaxError ...

Find the smallest key in the array using JavaScript's Object.keys(arr) and the reduce

In my experiment, I have 3 distinct scenarios which are fed into the function findMinDateAndMaxValue: {} { '2022-04-29': 1 } { '2022-04-29': 3, '2022-04-30': 2, '2022-04-28': 3, '2022-05-02': 2 } My obje ...

Passing the value in a td element to a JavaScript function using Thymeleaf onClick

Trying to utilize "Thymeleaf" for the first time, I am attempting to pass a value to JavaScript with the following code: onclick="getPropId('${properties.id}')" The corresponding function is as follows: getPropId(inputID){alert(inputId);} Unf ...

Populate a JSON table in React with checkboxes and automatically mark them based on the JSON data

I'm currently working on creating a React table using JSON data like this: [ { "Id_side": 123, "Name_side": "R4", "Name_cycle": "C1" }, { "Id_side": 345, "Name_side": "M1", "Name_cycle": "C2" ...

"Troubleshooting: ngForm.controls returning undefined value in Angular application

Trying to test this HTML code in Angular: <form name="formCercarUsiari" #formCercarUsuari="ngForm" class="tab-content"> <input #inputNif class="form-control input-height" maxlength="100" type="text" placeholder="Indiqui NIF" name="nif" i18n-pla ...

What is the best way to connect to a JSON key that is consistently returned with a varying or unpredictable name?

I am currently working on an Angular 4.x application where my goal is to showcase a random Wikipedia article. Each time I check the JSON data in Chrome Dev Tools under query/pages, I notice that the pageID always has a different number. The structure of th ...

Loading an ASP.net page on the client side

Can someone tell me the event for pageload on clientside? function onPageLoad() { setSelectedIndexTo(1); } I attempted to do this, however no changes occur. Appreciate any help. Thanks! ...

What is the best way to incorporate a smooth transition for an object as it appears on the screen in React?

After configuring my code to display a component in the HTML only if a specific hook is set to true, I encountered an issue with a CSS transition. The problem arises because the 'open' class is triggered at the same time the element becomes true, ...

Instructions on incorporating domains into next.config.js for the "next/image" function with the help of a plugin

Here is the configuration I am currently using. // next.config.js const withImages = require("next-images"); module.exports = withImages({ webpack(config, options) { return config; }, }); I need to include this code in order to allow images from ...

What is the best way to eliminate the alert message "autoprefixer: Greetings, time traveler. We are now in the era of CSS without prefixes" in Angular 11?

I am currently working with Angular version 11 and I have encountered a warning message that states: Module Warning (from ./node_modules/postcss-loader/dist/cjs.js): Warning "autoprefixer: Greetings, time traveler. We are now in the era of prefix-le ...

When you hover your cursor over specific keywords, they will light up and glow in the sentence or paragraph

Looking to create a sentence or paragraph like "I enjoy taking my dog for a walk." with categories such as "Nouns", "Verbs", etc. I envision the ability for users to hover over "Nouns" and have words like "dog" and "walk" light up, while hovering over "Ver ...

After attempting to refresh the webpage with the F5 key, I noticed that the jQuery progress bar was not functioning properly. Additionally, the webpage failed to display any

Trying to implement a web loading bar using jQuery on my website was initially successful, but I encountered an issue when reloading the page with F5. The progress bar would not work and the webpage displayed only a white background. Below is the code snip ...

Display or conceal certain HTML form elements based on the selection made in the previous form element

I need assistance with a function that can dynamically show or hide certain HTML form elements based on the user's previous selection using JavaScript. For example, if a user selects "Bleached" from the Dyingtype drop-down menu, there is no need to di ...

When working with React-Native App and combining React-Navigation with Redux, a common error may occur stating that 'action.routeName' is not an object. This issue can be

I encountered an error in my React Native app while implementing react-navigation within redux. The issue, along with a screenshot for reference, can be found here. Currently, I have not incorporated any redirects into the application. However, my plan in ...

Personalized design for Sweet alert 2

I am trying to customize a sweetAlert2 by defining a className, but it seems that the styling is not applying to the sweet alert. I have tried calling the class name "styleTitle" and various other names, but nothing seems to work. Could the issue be with t ...

EJS forEach method not displaying output

Trying to work with this .ejs file that's supposed to loop through an object and retrieve data from an API. However, after fetching the data, it appears that nothing is being displayed on the screen. I've checked the API results in the console l ...

What steps should I take to ensure the text layout algorithm effectively scales the text based on the "font size" option when using SVG paths?

I have included a fully functional JavaScript code snippet at the end of this post, demonstrating how Hebrew text can be displayed in a "stretched" layout design, as referenced here. The output shows the text in various font sizes: 32 The text appears mos ...

Steps for removing an item from an array in MongoDB

Is it possible to remove an object from the mainList array? _id:ObjectId("5fafc5aec2b84c301845c55a"), username:"test", mainList:[ { _id:ObjectId("5fafdf1a5b49510c789af0ae"), n ...

Unexpected outcome when utilizing localeCompare options in Node.js

Comparing Output from CLI and Chrome Console: > var a = 'foo12'; undefined > var b = 'foo3'; undefined > var s = [a , b]; undefined > s.sort(function(a, b) { ... return a.localeCompare(b, 'en', { numeric: true }); ...