1

in my vue template i have this...

<template>
   <div id="container">
      {{show_municipality_in_words(12)}}
   </div>
</template>

in my js...

export default {
   data() {
   },
   methods: {
     show_municipality_in_words(municipality_id) {
      fetch(`api/biodidb/get_municipality_name_by_id/${municipality_id}`)
       .then(response => response.json())
       .then(result => {
         console.log(result.Municipality);
         return result.Municipality;
       }).catch(err => {console.log(err)});
     }
   }
}

in html view, it returns nothing but in console it has the data.. is this the proper way of displaying it?

Jiel
  • 103
  • 1
  • 2
  • 12

1 Answers1

0
  1. Your method doesn't return anything so there's nothing to render.
  2. Your method is asynchronous so you could not return any value even if you wanted to.

TL;DR try to avoid using methods in your templates and instead, load data into your data properties. For example

<template>
  <div id="container">
    <span v-if="municipality">{{ municipality }}</span>
    <span v-else>Loading...</span> <!--  totally optional -->
  </div>
</template>
data () {
  return { municipality: null }
},
methods: {
  loadMunicipality (id) {
    return fetch(`api/biodidb/get_municipality_name_by_id/${id}`)
        .then(res => res.json())
        .then(obj => obj.Municipality)
  }
},
created () {
  this.loadMunicipality(12).then(municipality => {
    this.municipality = municipality
  }).catch(err => {
    console.error(err)
  })
}
Phil
  • 157,677
  • 23
  • 242
  • 245
  • if i do this: show_municipality_in_words(municipality_id) {return 'hello'}.. it returns the string hello.. but if inside fetch it returns nothing. why is that? – Jiel Jan 03 '19 at 05:40
  • Because `fetch` is asynchronous. See [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Phil Jan 03 '19 at 05:40