h.and.h
h.and.h

Reputation: 776

In Vue, how do I set a data property from a method on load?

I'd like to have a data prop populated by data received from an axios http request. Here's a simplified version of the issue.

I would like the 'hello' prop to populate when the app loads. And when the user clicks the button, the 'hello' prop should update. The click-and-update part is working as expected, but how do I get the data to populate the 'hello' prop initially? I've also tried it with computed properties, but that also doesn't populate the 'hello' prop on the initial load. Thanks!

<div id="app">
  <h1>{{ hello }}</h1>
  <button @click="updateText()">Update text!</button>
</div>

var app = new Vue({
  el:'#app',
  created() { 
    updateText() // Calling this here does not work
  },
  data: {
    hello: ''
  },
  methods: {
    updateText: function() {
      this.hello = 'hello'
    }
  }
});

Upvotes: 0

Views: 487

Answers (1)

Un1
Un1

Reputation: 4132

You don't have this. before the method name inside created so it's not calling the method:

var app = new Vue({
  el: '#app',
  data: function() {
    return {
      hello: ''
    }
  },
  created () { 
    this.updateText()
  },
  methods: {
    updateText: function() {
      this.hello = 'hello'
    }
  }
})

Upvotes: 1

Related Questions