user4383363
user4383363

Reputation:

Render form after method completion in VueJS

I am facing a problem with my page with VueJS. It's a page for different translations of the website. It has a dropdown on the top for the language selection that once switched will update the fields with the current language.

The problem starts when it loads, because my form is like this:

<form id="trForm">
    ...
    <input type="text" name="header_title" class="form-control" v-model="translations.header.header_title" />
    ...
</form>

It's trying to access these attributes before the method returns any data, but somehow it will still show the data once it is complete, but it becomes troublesome when I try to switch the language, it won't because of this problem and also, if I do the following:

<form id="trForm">
    ...
    <input type="text" name="header_title" v-if="translations.header" class="form-control" v-model="translations.header.header_title" />
    ...
</form>

on each field, those that aren't populated will display no field at all for a new input value. I tried something like translations.features || '', but no success.

I also tried to put on the parent block a condition that if the loading is false will display the form, but since the page is loaded first than the method is executed, it will always be false for the first microsecond.

methods: {
    fetchTranslations(e) {
        let vm = this;
        vm.loaded = false;
        $.get('/ajax/admin/translations', { 'locale': e }).done((data) => {
            if (data.success) {
                vm.translations = JSON.parse(data.translations.translation);
                vm.loaded = true;
            } else {
                toastr.error('Something went wrong');
            }
        });
    },

Please, what do I do? It'd be good to show the form after there is data.

Upvotes: 0

Views: 525

Answers (1)

vzwick
vzwick

Reputation: 11044

  • Introduce a new variable, e.g. loaded that defaults to false
  • Use this variable as a v-if condition on the form
  • In the callback of your data fetch, set loaded to true.

Upvotes: 1

Related Questions