Skip to content
Advertisement

How to initiate a function using data(){} but not mounted(){} while using vue-resource

This works, but I need to use mounted(){} to initiate the function which I think can be avoided but not sure how.

<script>
  export default {
    data () {
      return {
        domains: [],
      }
    },

    methods: {
      fetchDomains() {
        let _this = this;

        api._get({url: 'api/domains'})
          .then(function (response) {
            _this.domains = response.data;
          })
      }
    },

    mounted() {
      this.fetchDomains()
    }
  }
</script>

This code doesn’t work, but I like to do something like this. Initiating the function in data(){} itself.

<script>
  export default {
    data () {
      return {
        domains: this.fetchDomains(),
      }
    },

    methods: {
      fetchDomains() {
        let data = [];

        api._get({url: 'api/domains'})
          .then(function (response) {
            data = response.data;
          })

        return data
      }
    }
  }
</script>

Thanks in advance.

Advertisement

Answer

I agree with Decade Moon that your first approach is the better way to do it (though you could use created instead of mounted).

The reason your second approach doesn’t work is that you return an array and then replace the local variable’s value with a different array. What you need to do is populate the array you returned.

new Vue({
  el: '#app',
  data() {
    return {item: this.getItem()}
  },
  methods: {
    getItem() {
      let val = [];
      setTimeout(() => {
        const result = ['first','second','third'];
        val.push(...result);
      }, 800);
      return val;
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">{{item}}</div>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement