0

I'm new to VueJS and have a very basic question. If I have a JS variable and want to parse it into a Vue instance data section how can this be done? In my simple example below I want to parse my variale "parsedJSON" into Vue instance "mainVue" under data section in the variable called "test":

let parsedJSON = fetch(url)
    .then(function(response){
        return response.json();
    }).then(function (data){
        console.log(data)
});

let mainVue = new Vue({
    el: '#mainContent',
    data: {
        test: ""
    }
})

In my entire code the "parsedJSON" variable consist of JSON data from a mongoDB, which is fetched fine, but I cant seem to find a way to parse it into my Vue instance. The correct data is displayed in the console.

2
  • you should fetch within the vue instance, in beforeMount for example Commented Oct 31, 2020 at 11:44
  • Yeah that's what I thought. Just not sure how to do that tbh. Commented Oct 31, 2020 at 11:45

2 Answers 2

2

Try this, fetch within the instance:

let mainVue = new Vue({
  el: '#mainContent',
  data: function() {
    return {
        test: {}
    }
  },
  created() {
    fetch('...').then(function(response) {
      return response.json();
    }).then(function(data) {
      this.test = data;
    }.bind(this))
  }
})

or a little bit more tidier

let mainVue = new Vue({
  el: '#mainContent',
  data: () => ({
    test: {}
  }),
  async created() {
    this.test = await fetch('...').then(res => res.json())
  }
})
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you! This worked for me. I'll look up the beforeMount, as I'm not familiar with this.
np, thanks for accept, also to tidy up the code you could use async/await and arrow funcs instead of .bind(this), depends on IE support as doesn't look like your using a transpiler
though saying that fetch is also not in IE ;p
Thanks for the tip and the answer again. I just had a look, and seems like I can use "created" for this, instead of beforeMount, right? To call synchronously after the instance is created
also if test is an object, define it as object in data.. test: {}
|
0

Did you try just setting it like this?

    data: {
        test: parsedJSON
    }

2 Comments

Yes and this will work with a "normal" varialbe. The thing is, that in my parsedJSON I'm fetching data from my mongo db, and it will not let me parse it that way. I will change/update the code example above.
Ah I understand now, in which case I think the other answer is correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.