peschanko
peschanko

Reputation: 363

So how can I update or re-render my html template on dynamically changed property using VueJS?

I have a VueJS template with Bootstrap 4 modal dialog inside it:

<script type="text/x-template" id="vue-case-select">

 <div class="modal fade" id="case-select" tabindex="-1" role="dialog" aria-labelledby="caseLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable" role="document" ref="container">
    <div class="modal-content">
      <div class="modal-header"> ... </div>
      <div class="modal-body">
       <div class="modal-container">

        <!-- This property must be reactive and re-rendered -->
        <input type="text" class="form-control" v-model="title">

       </div>
      </div>
    </div>
  </div>
 </div>

</script>

And a component corresponding the template:

Vue.component('vue-case-select', { 
    template: '#vue-case-select',
    props: [
        'predefined_title',         
    ],
    data() {
        return {
            title: '',
        }
    },
    mounted: function() {
        // Updating current title and it works
        this.title = this.predefined_title;
    },
});

Everything works just fine statically. But I want to change value of the input[type=text] inside my dialog depending on a parent component of user's choice. I'm trying to do it this way:

// This code is executed in a method of another VueJS component which has
// its own title

const MyCase = Vue.extend(VueCaseSelect);
const vm = new MyCase({
    parent: this,
    propsData: {
        // Passing title to modal dialog and it works
        predefined_title: this.title,
    },
});

vm.$mount('#some-element-id');

I know for sure that property title is changed correctly on mounted event inside vue-case-select component each time I create a new MyCase object. But I cannot figure out how to make input[type=text] control update its value according to v-model.

So how can I update or re-render my html template on dynamically changed property using VueJS?

I have tried computed, watch and $nextTick() but may be I did it the wrong way?

UPD: May be it needs to be mentioned that this code works only once. For the first time I can see a dialog with a title shown, but when I close it and click on another component, the title variable in VueJS in correct state, but the input[type=text] still contains the previous title value.

Upvotes: 0

Views: 1252

Answers (1)

Qonvex620
Qonvex620

Reputation: 3972

Did you try to use watcher ? like this one

watch: {
   predefined_title(val) {
      this.title = val
   }
}

Or, put a condition in your input to prevent showing it when predefined_title is empty.

<input type="text" class="form-control" v-model="title" v-if="predefined_title">

Or, destroy your component to remove it in the vue instance like this below

beforeDestroy () {
    this.$el.parentNode.removeChild(this.$el);
    $('.modal-backdrop').hide();
},

Upvotes: 1

Related Questions