2017-02-19 154 views
0

我正在使用vuejs路由器構建單頁應用程序。 路由器工作正常,但我想在路由到組件後加載特定的腳本。Vuejs在路由後加載js文件

水木清華這樣的:

const Mine = { 
    template: ' <div>Another</div>', 
    load_script: <script src="/static/script.js"></script> 
} 

我怎樣才能做到這一點?

現在我有當前塊的html:

<div id="routing"> 
    <router-view></router-view> 
</div> 

這是JS:

const Mine = {template: ' <div>Another</div>'} 

const routes = [ 
    { path: '/mine', component: Mine }, 
] 

const router = new VueRouter({ 
    routes, 
}) 

const app = new Vue({ 
    router 
}).$mount('#routing') 

回答

0

您可以加載腳本的HTML模板本身,因爲它是做加載任何文件從HTML,您可以有以下在您的模板:

const Mine = { 
    template: '<div> \ 
        <script src="/static/script.js"></script> \ 
        <div>Another</div> \ 
       </div>',  
} 
+0

Smth奇怪發生在我身上。即使'const bar = {template:'

First
Second
'}'不起作用。只顯示「第一」,不存在「第二」。因此只有你的例子執行腳本。不要看到'Another' – Snobby

+1

@Snobby嘗試在div中的'template'塊中包裝所有內容,如下所示:'const Bar = {template:'

First
Second
'}' – Saurabh

+0

'div's inside ''div運作良好,謝謝。但是這個技巧不適用於'script'。所以'const bar = {template:'

First
'}'當然不是,也不是'const Bar = {template:'
First
' }'只執行第一個標籤。 – Snobby