简体   繁体   中英

Vue.js does an event trigger after component has been rendered?

I've got some custom components in Vue.js. In one of the components I have is a select list that I want to render as a Chosen select box. I use this with a jQuery function $("select").chosen() .

<template v-for="upload in uploads">
    <new-upload-container :index="$index" :upload="upload" v-if="isNewUpload"></new-upload-container>
    <existing-upload-container :index="$index" :upload="upload" v-if="isExistingUpload"></existing-upload-container>
</template>

After I add data to the uploads bound array in the Vue instance, the view updates with an instance of the component. Unfortunately when I try to instantiate Chosen on the select field, it doesn't work.

I'm not sure if it takes a short time after I add an item to the uploads bound array that the DOM actually updates.

<template id="existing-upload-container">

      <select name="beats[@{{ index }}][existing_beat]" class="existing-beats">
           <option selected="selected" value="">-- Select a linked beat --</option>
                  @foreach ($beats as $beat)
                   <option value="{{$beat->id}}">{{$beat->name}}</option>
                  @endforeach
       </select>

    </template>

Is there an event that is triggered after a component has been fully rendered?

The correct way would be a custom directive :

<select v-chosen name="beats[@{{ index }}][existing_beat]" class="existing-beats">

//insert/require() the following before the creation of your main Vue instance
Vue.directive("chosen",{
  bind: function(){
    $(this.el).chosen();
  }
})

edit: directive syntax changed in Vue 2.*:

Vue.directive("chosen",{
  bind: function(el){
    $(el).chosen();
  }
})

You could try two things in your component, based on which one works with your package. In the Vue object:

{
    ready:function(){
        // code here executes once the component is rendered
        // use this in the child component
    },
    watch: {
        uploads:function(){
            //code here executes whenever the uploads array changes 
            //and runs AFTER the dom is updated, could use this in
            //the parent component
        }
    }
}

使用mounted回调并检查代码中的数据状态。

做一个很好的好方法是将包裹已选择插件在Vue的组件,如详细说明这里

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM