How to define property or method on the instance before render

Viewed 783

I am learning Laravel with Vue.js, and I am facing a problem which I have not been able to resolve the problem either by studying the Laravel and Vue.js manuals or by sifting through the internet.

I have a blade.php-file where I make use of a vue-template. The template is called Articles.Vue and it is supposed to appear between two -tags.

There is a problem with rendering. I have a file called app.js, where I require Articles.vue:

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
});

The file Articles.vue namens looks as follows:

<template>
    <div>
        <div>Das sollte dann durch axios befüllt werden...
                {{ display() }}
       </div>
    </div>
</template>

Now somehow the display-method (which I intend to use for an ajax-call) remains unknown on rendering:

[Vue warn]: Property or method "display" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

My plan was to define the display() - method in app.js and to put it into the vue's data-section, to no avail. What did I do wrong?

1 Answers

data is a method called by Vue when initializing, it must return an object which is going to be the local state of the component. In your code, you return nothing in this function, resulting in the component having no state.

data cannot be an asynchronous function (returning a Promise), so what you should do instead is define it’s default state in there and only later, load the data from the server and store it. Vue will automatically re-render the component when data changes.

It should look something like this:

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;
      });
  }
});

And your template would look like this:

<div>
  <div>Das sollte dann durch axios befüllt werden...</div>
  <div v-if="pizza">{{ pizza }}</div>
</div>
Related