2016-11-15 1149 views
1

我google了很多,但沒有發現任何關於此。如何在渲染Vue組件時觸發事件?

我想在Vue渲染時淡入我的內容。我的應用程序很大,需要一段時間才能爲用戶做好準備。但是,當Vue將內容插入塊時,CSS動畫不想工作。請參閱下面列出的代碼JSFiddle

HTML

<div id="my-app"> 
    <p>Weeverfish round whitefish bass tarpon lighthousefish mullet tigerperch bangus knifefish coley Black sea bass tompot blenny madtom tapetail yellow-eye mullet..</p> 

    <hr> 

    <example></example> 
</div> 

CSS

#my-app { 
    opacity: 0; 
    transition: 2s; 
} 

#my-app.visible { 
    opacity: 1; 
    transition: 2s; 
} 

的JavaScript

// Fade in animation will work if you comment this ... 
Vue.component('example', { 
    template: `<p>Starry flounder loach catfish burma danio, three-toothed puffer hake skilfish spookfish New Zealand sand diver. Smooth dogfish longnose dace herring smelt goldfish zebra bullhead shark pipefish cow shark.</p>` 
}); 

// ... and this 
const app = new Vue({ 
    el: '#my-app', 

    // Makes content visible, but don't provides fade-in animation 
    /* 
    created: function() { 
     $('#my-app').addClass('visible') 
    } 
    */ 
}); 

// Makes content visible, but don't provides fade-in animation 
// with enabled Vue 
$('#my-app').addClass('visible'); 

// As you can see, animation with Vue works only here 
setInterval(() => { 
    $('#my-app').toggleClass('visible'); 
}, 5000); 

而且我也沒有發現任何內置Vue解決方案(事件,方法等)在渲染Vue時運行代碼。像load & DOMContentLoaded這樣的事件也沒有幫助。 created也沒有提供預期的結果:

const app = new Vue({ 
    el: '#my-app', 
    // Makes content visible, but don't provides fade-in animation 
    created: function() { 
     $('#my-app').addClass('visible') 
    } 
}); 

有誰知道我的問題很好的解決方案?

謝謝。

+0

您使用的是哪個版本的Vue?可以在VueJS 2中以編程方式處理轉換,並且您希望使用掛載的鉤子而不是'created'鉤子,因爲到那時它將被應用到DOM。 –

+0

@DavidL,似乎將'created'更改爲'mounted'沒有幫助。我正在使用Vue的最新版本。好的,謝謝,我現在嘗試使用轉換。 – terron

+0

如果可能的話,我肯定會推薦vue通過鉤子的外部解決方案進行轉換。 –

回答

1

非常感謝@David L@Bill Criswell指向Transition Effects。我已經取得了預期的結果與此代碼:

HTML

<div id="my-app"> 
    <app> 
     <p>Weeverfish round whitefish bass tarpon lighthousefish mullet tigerperch bangus knifefish coley Black sea bass tompot blenny madtom tapetail yellow-eye mullet..</p> 

     <hr> 

     <example></example> 
    </app> 
</div> 

CSS

.fade-enter-active, .fade-leave-active { 
    transition: opacity 1s 
} 

.fade-enter, .fade-leave-active { 
    opacity: 0 
} 

的JavaScript

Vue.component('app', { 
    data: function() { 
     return { 
      show: false 
     } 
    }, 
    mounted: function() { 
     this.show = true; 
    }, 
    template: `<div> 
     <transition name="fade"> 
      <div v-if="show"> 
       <slot></slot> 
      </div> 
     </transition> 
    </div>`, 
}); 

Vue.component('example', { 
    template: `<p>Starry flounder loach catfish burma danio, three-toothed puffer hake skilfish spookfish New Zealand sand diver. Smooth dogfish longnose dace herring smelt goldfish zebra bullhead shark pipefish cow shark.</p>` 
}); 

const app = new Vue({ 
    el: '#my-app', 
}); 

這裏有JSFiddle的工作結果。