Skip to content
Advertisement

Vue.js component method on creation

I’m new to Vue and I’d like to make an AJAX call every time my component is rendered. I have a vue component lets say “test-table” and Id like to fetch the contents via an AJAX call. There are many such tables and I track the active one via an v-if/v-else-if etc.

Currently I have a cheaty solution: in the template for the component I call a computed property called getData via
{{ getData }}
which initiates the Ajax call but does only return an empty string. Id like to switch to the proper way but dont know how.

My code is like so: (its typescript)

Vue.component("test-table", {
        props: ["request"],
        data () {
            return {
                tableData: [] as Array<TableClass>,
            }
        },
        template: `{{ getData() }} DO SOME STUFF WITH tableData...`,
        computed: {
            getData() : string {
                get("./foo.php", this.request, true).then(
                    data => this.tableData = data.map(element => new TableClass(data))
                )
                return "";
            }
        }
}

HTML:

<test-table v-if="testcounter === 1" :request="stuff...">
<test-table v-else-if="testcounter === 2" :request="other stuff...">
...

get is an async method that just sends a GET request with request data to the server. The last parameter is only for saying the method to expect a JSON as answer. Similar to JQuerys getJSON method.

the “created” method does NOT work! It fires only one time when the component is first created. If I deactivate and activate again (with v-if) the method is not called again.

Btw: I’m using Vue 2.6.13

Advertisement

Answer

Lifecycle hooks won’t fire every time if the component is cached, keep-alive etc

Add a console.log in each of the lifecycle hooks to see.

Change to use a watcher which handles firing getData again if request changes.

  ...
  watch: {
    request: {
      handler: function() {
        this.getData()
      },
      deep: true
    }
  },
  created() {
     this.getData()
  },
  methods: {
    getData(): string {
      // do request
    }
  }
Advertisement