【问题标题】:Vuejs load js file after routingVuejs在路由后加载js文件
【发布时间】:2017-07-08 22:39:29
【问题描述】:

我正在使用 vuejs 路由器构建单页应用程序。 路由器运行良好,但我想在路由到组件后加载特定脚本。

喜欢:

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

【问题讨论】:

    标签: javascript vue-component vue-router


    【解决方案1】:

    您可以在 HTML 模板本身中加载脚本,就像从 HTML 加载任何文件一样,您可以在模板中包含以下内容:

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

    【讨论】:

    • 奇怪的事情发生在我身上。即使const Bar = { template: '&lt;div&gt;First&lt;/div&gt;&lt;div&gt;Second&lt;/div&gt;' } 也不起作用。仅显示 First 不存在 Second。因此,只有从您的示例执行的脚本。看不到Another
    • @Snobby 尝试将 template 块中的所有内容包装在 div 中,如下所示:const Bar = { template: '&lt;div&gt;&lt;div&gt;First&lt;/div&gt;&lt;div&gt;Second&lt;/div&gt;&lt;/div&gt;' }
    • 带有div 的东西在div 里面运行良好,谢谢。但是这个技巧不适用于script。所以const Bar = { template: '&lt;div&gt;&lt;div&gt;First&lt;/div&gt;&lt;script&gt;console.log("Hooray")&lt;/script&gt;&lt;/div&gt;' }当然不起作用,const Bar = { template: '&lt;div&gt;First&lt;/div&gt;&lt;script&gt;console.log("Hooray")&lt;/script&gt;' }只有第一个标签执行。
    • 这个帖子似乎暗示 Vue 从模板中去除
    猜你喜欢
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    相关资源
    最近更新 更多