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>
`});

posted on   完美前端  阅读(1469)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2019-04-03 搜索算法
2019-04-03 排序算法,冒泡排序,选择排序,插入排序,归并排序

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示