問題描述
在一個使用傳統 `.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> `});