Vue.js在渲染组件后执行事件触发器?

Was*_*sim 19 javascript vue.js

我在Vue.js中有一些自定义组件.我在其中一个组件中是一个选择列表,我想将其呈现为选择选择框.我用jQuery函数$("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>
Run Code Online (Sandbox Code Playgroud)

在将数据添加到uploadsVue实例中的绑定数组后,视图将使用该组件的实例进行更新.不幸的是,当我尝试Chosen在select字段上实例化时,它不起作用.

我不确定在将项目添加到uploadsDOM实际更新的绑定数组后是否需要很短的时间.

<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>
Run Code Online (Sandbox Code Playgroud)

是否有一个事件在组件完全呈现后触发?

Lin*_*org 10

正确的方法是自定义指令:

<select v-chosen name="beats[@{{ index }}][existing_beat]" class="existing-beats">
Run Code Online (Sandbox Code Playgroud)
//insert/require() the following before the creation of your main Vue instance
Vue.directive("chosen",{
  bind: function(){
    $(this.el).chosen();
  }
})
Run Code Online (Sandbox Code Playgroud)

编辑:在Vue 2中更改了指令语法.*:

Vue.directive("chosen",{
  bind: function(el){
    $(el).chosen();
  }
})
Run Code Online (Sandbox Code Playgroud)


Jef*_*eff 9

您可以在组件中尝试两种方法,具体取决于哪种方法适用于您的包.在Vue对象中:

{
    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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在+1之后,它看起来像在vuejs 2`ready`被替换为`updated`,看看这里:https://vuejs.org/v2/guide/instance.html我测试`ready`它没有工作 (8认同)
  • @MajedDH我相信正确的一个将被"挂载",因为更新的内容不止于此.我无法使用`ready`,但`mount`按预期工作. (4认同)