html中使用引入vue公共组件


问题描述

在一个使用传统 `.html` 文件搭建的vue项目中,Vue 只被用作数据渲染工具。每个页面都有相同的 header 和 footer,
导致有大量重复代码。现在的目标是将 header 和 footer 提取出来,使代码更加整洁。

解决办法

1. 将公共部分(如 header 和 footer)写入一个 `.js` 文件中。这些文件的本质是在当前页面中定义的公共 Vue 组件。
2. 组件的模板可以使用字符串拼接(如果内容较少),或者使用模板字符串。

 

完整的代码, 可以复制引用

 

index.html 文件内容

<!doctype html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>test</title>
</head>
<body>
<div id="vue_app">
    <!-- 使用自定义的头部组件 -->
    <common-head></common-head>
perl
Copy code
<!-- 页面独有的内容 -->
<div style="background: #fba">我是内容</div>
    </div>

    <!-- 引入Vue库 -->
<script type="text/javascript" src="vue.js"></script>
    <!-- 引入公共头部组件 -->
<script type="text/javascript" src="header.js"></script>
<script type="text/javascript" src="home.js"></script>
<script>
const home = { template: '<common-content></common-content>' }
const router = new VueRouter({
    routes: [
        { path: '/home', component: home },
        { path: '/about', component: about },
        { path: '/safety', component: safety },
        { path: '/help', component: help },
        { path: '/moving', component: moving },
        { path: '*', redirect: '/home'}
    ]
});

new Vue({
    router,
    mounted() {
    }
}).$mount("#app");
</script>
</body>
</html>

header.js 文件内容

// 定义一个公共头部的 Vue 组件
Vue.component('common-header', {
template: `
<div class="animate-route">
    2222
</div>
`});


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM