Home > Enterprise >  Rendering variables from async functions in VueJs
Rendering variables from async functions in VueJs

Time:07-09

I'm pretty new to VueJs. My intention is to create a simple application that extracts the text from a wikipedia page and renders it on a button press.

Code

<script>
const wiki = require('wikipedia');
export default {
    data() {
        sum:"hello"
    },
    methods: {
        async getWiki() {
            try {
                const page = await wiki.page('Batman');
                console.log(page);
                //Response of type @Page object
                const summary = await page.summary();
                console.log(summary.extract);
                //Response of type @wikiSummary - contains the intro and the main image
                this.sum = summary.extract
            } catch (error) {
                console.log(error);
                //=> Typeof wikiError
            }
        }
    }
}
<template>
    <span>{{sum}}</span>
    <button @click="getWiki()">Get Wiki</button>
</template>

Errors

[Vue warn]: Property "sum" was accessed during render but is not defined on instance. at <Main>

and

[Vue warn]: data() should return an object. at <Main>

But all the console.logs work properly when the button is pressed

CodePudding user response:

try adding return statement for data

data() {
  return {
    sum: "hello"
  }
}
  • Related