Vue.js does an event trigger after component has b

2019-04-18 05:10发布

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?

4条回答
劳资没心,怎么记你
2楼-- · 2019-04-18 05:43

use mounted callback and check the data status in your code there.

查看更多
The star\"
3楼-- · 2019-04-18 05:51

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
        }
    }
}
查看更多
Emotional °昔
4楼-- · 2019-04-18 05:58

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();
  }
})
查看更多
做自己的国王
5楼-- · 2019-04-18 06:00

A good good way to do this would be to wrap the Chosen plugin in a Vue component, as described in detail here.

查看更多
登录 后发表回答