Creating a property or method on the instance prior to rendering

During my journey of learning Laravel and Vue.js, I encountered a challenging issue that has proven to be quite perplexing. Despite delving into the depths of Laravel and Vue.js documentation, as well as scouring the internet for solutions, I remain unable to resolve this particular problem.

The predicament revolves around a blade.php file where I have implemented a vue-template named Articles.Vue, intending for it to appear nestled between two specific tags.

The source of trouble lies in the rendering process. Within my app.js file, I am requiring Articles.vue as follows:

require('./bootstrap');

window.Vue = require('vue');

Vue.component('articles', 
require('./components/Articles.vue').default
);

var display = () => {  
           axios.get('http://localhost/project/public/pizzas/0').then(resp => {
              return JSON.stringify(resp.data);
  });
};

const app = new Vue({
    el: '#app',
    data: display
});

This Articles.vue file appears structured like so:

<template>
    <div>
        <div>This should be populated by axios...
                {{ display() }}
       </div>
    </div>
</template>

However, despite my intentions for utilizing the display() method for an ajax call, it remains unidentified during the rendering process:

[Vue warn]: Property or method "display" is not defined on the instance but referenced during render. Ensure that this property is reactive, either within the data option, or for class-based components, through proper initialization of the property.

My initial approach was to define the display() method within app.js and incorporate it into the data section of Vue, yet my efforts proved futile. Where exactly did I go wrong?

Answer №1

data is a crucial method that Vue calls during initialization. Its purpose is to return an object that will serve as the local state of the component. If this function does not return anything, the component will end up with no state.

data cannot be an asynchronous function that returns a Promise. Instead, you should set the default state within this method and fetch data from the server later on. Vue will take care of re-rendering the component whenever the data changes.

Your implementation should resemble something like the following:

const app = new Vue({
  el: '#app',

  data() {
    return {
      pizza: null,
    }
  },

  created() {
    axios.get('http://localhost/project/public/pizzas/0')
      .then(resp => {
        this.pizza = resp.data;
      });
  }
});

Your template structure should look similar to this:

<div>
  <div>This section will be populated by axios...</div>
  <div v-if="pizza">{{ pizza }}</div>
</div>

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 functionality of $watch is not functioning correctly within the Modal, despite implementing it with $scope.user={pwd1:''}

For the Plunker link referenced, please click here: http://plnkr.co/edit/0vOjw0?p=preview index.html <!DOCTYPE html> <html ng-app="app"> <head> <link rel="stylesheet" href="style.css"> ...

Steps for generating a pop-up window for choosing a file from a local folder?

I'm looking to develop a popup window that displays all the files within a specific directory, for example, a /functions directory. The goal is to be able to select a file in that directory, click "ok", and store its information in variables without a ...

I am looking to superimpose one rectangle over another rectangle

I am looking to create something similar using CSS and TypeScript/JavaScript: Could someone please guide me on how to achieve this? My attempt with a flex container looks like this: I am new to front-end development. Can anyone point out what I might be ...

Discover the smallest and largest values within the multi-layered object

My JavaScript object is deeply nested with an infinite number of children, each containing a value. var object = { value: 1, children: { value: 10, children:{ value: 2, children: {...} } } } I've tried ...

Utilizing jQuery to access Flash functions

When trying to access functions in my SWF using jQuery code, I encounter a compatibility issue with Internet Explorer. The code works fine in all other browsers except for IE. As jQuery is supposed to provide cross-browser functionality, writing addition ...

What is the best way to share variable values between different components in React?

I initially assumed that setting a prop would handle the value within the receiving component, but now I realize that I want to export the value to other components. For example, consider this reusable component: RegionButtons.jsx file import React, { us ...

I prefer not to have my preceding component re-rendered in React

I'm currently working on developing a user interface for a search engine using elasticsearch within React. One issue I'm facing is with the Pagination technique - when a user clicks on a result and then navigates back to the list of results, it r ...

How to Refresh Javascript Functionality in Rails 5 after an Ajax Update?

After exploring my Javascript issue, I've identified the problem post an AJAX call that refreshes a div's content. The core issue is that the contents within the div become unlinked or uninitialized for the Javascript. My goal is to allow users t ...

"Encountering an error: invalid CSRF token in Node.js csurf

I have been utilizing the npm module csurf to generate a token. Initially, I retrieve the token from the server and then utilize it for the /register request. When I replicate these steps in Postman, everything seems to function correctly, but unfortunatel ...

Troubleshooting the malfunction of the CSS display property

I've created a div with a number displayed initially. When I hover over the div, the number disappears and a paragraph is revealed. Upon hovering out, the paragraph hides and the number reappears. My attempts to achieve this using CSS (display: none ...

Ways to display an array of objects based on their duplicate values

Struggling with the following example, seeking assistance new Vue({ el:"#app", data: { items: [ { type: "a", Descr: "searching" }, { type: "a", Descr: "maps" ...

When a dropdown list only contains one item, the jQuery change event does not get triggered

I'm currently exploring ways to trigger events when options in a dropdown menu are clicked. I haven't come across any clear explanations on how to achieve this. What I specifically need is to activate the event and utilize the selected value. Usi ...

Repetitive points detected in three.js typography

I converted a ttf font to a js font for three.js using Facetype.js, but I am encountering multiple duplicate point errors such as: THREE.Shape: Duplicate point 41.52:10.928 THREE.ShapeUtils: Unable to triangulate polygon! in triangulate() What steps ...

Move the navigation bullets of the Nivo Slider to the bottom instead of below the slider

Currently working on a website and have incorporated Nivo Slider to develop a jQuery slider. Encountering an issue with the bullets that indicate which slide the user is currently viewing. I'd like these bullets to be displayed on the images within t ...

What sets apart simple value state from object state in React?

Are there any distinctions between organizing component state as a single object bundle like this (1) const [state, setState] = useState({ title: 'Jerome Is Coming!', year: '1998' }) versus managing separate states with primitive ...

The Xrm.Navigation function has not been defined

When attempting to open a modal dialog box, I used the following code: var addParams = "entityid=" + Xrm.Page.data.entity.getId() + "&entityName=" + Xrm.Page.data.entity.getEntityName(); var webresourceurl = "/webresources/pdfflr_selectorpage.html?Dat ...

Change the WordPress Divi Builder nav bar to switch from transparent to white when scrolling or upon reaching a specific point on the page

Currently, I am in the process of revamping our company's WordPress website using the Divi Builder. For the past couple of days, I have been scouring the internet trying to find a solution that would allow the navigation bar to change CSS classes as t ...

Utilize the Twitter Bootstrap modal feature to play autoplaying Youtube videos that automatically pause when

Similar Question: How do I halt a video using Javascript on Youtube? I am curious about how I can utilize the modal feature in Twitter Bootstrap to automatically play a Youtube video, and when a user clicks the "close" button, it will cease the video ...

The Vuetify v-img component fails to display images when using absolute paths

Having a bit of trouble here: I want to showcase an image using an absolute path in Vuetify with the v-img tag, but for some reason, it's not displaying. I attempted to use :src="require('path/to/img')", but it throws an error saying "This ...

The Angular application is experiencing issues following an update from version 11 to version 12

I recently updated my Angular project following these steps: npm cache clean --force npm uninstall @angular/cli@latest @angular/core@latest npm install -g @angular/cli@latest @angular/core@latest After completing the above steps, I proceeded to delete th ...