2016-01-25 63 views
18

Vue.jsにカスタムコンポーネントがあります。私が持っているコンポーネントの1つに、Chosen選択ボックスとしてレンダリングする選択リストがあります。私はこれをjQuery関数$("select").chosen()で使用します。コンポーネントがレンダリングされた後、Vue.jsはイベントトリガーを行いますか?

<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> 

IはVueのインスタンス内uploads結合したアレイ、コンポーネントのインスタンスを有するビューの更新にデータを追加した後。残念ながら、選択フィールドにChosenをインスタンス化しようとすると、それは機能しません。

uploadsバインドされた配列にDOMを実際に更新するアイテムを追加してから少し時間がかかりますかどうかわかりません。

<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> 

コンポーネントが完全にレンダリングされた後にトリガーされるイベントはありますか?

答えて

8

あなたのコンポーネントで2つのことを試すことができます。どちらに基づいてパッケージで動作するかを判断できます。 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 
     } 
    } 
} 
+8

+1の後に、それはvuejs 2のように見えます。 'ready'が' updated'に置き換えられました。ここを見てください:https://vuejs.org/v2/guide/instance.html 私は 'ready 'それはうまくいきませんでした。 –

+3

@MajedDH私は正しいものが' mounted'と考えています。私は 'ready'で動作させることができませんでしたが、' mounted'は期待どおりに動作しました。 – asselinpaul

+0

@asselinpaul、彼らは異なっています。非同期ロードされたデータから動的に作成された要素へのバインドの問題を解決することはできません。更新された作品はこちら –

10

正しい方法は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(); 
    } 
}) 

編集:ディレクティブの構文は、Vueの2 *に変更:

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

これは、[受け入れられた回答](http://stackoverflow.com/a/34997958/368864)よりも洗練されたソリューションのように聞こえます。 – cambraca

+0

がありません。 before selected()? – Kokizzu

+1

ありがとうございました。また、この構文はVue 1でのみ機能することにも注意してください。 –

0

これを行う良い方法は、ChosenプラグインをVにラップすることです詳細にはhereに記載されているように、

関連する問題