問題描述:
整體項目采用傳統 .html 文件搭建,vue僅作為渲染數據工具使用,需要使用的地方使用 <script> 標簽引入。
現有數個頁面,每個頁面都包含相同 header 和 footer ,希望可以把 header 和 footer 提取出來,避免太多重復代碼。
解決辦法
公共部分寫在 .js 文件里,本質就是在當前頁面中寫的公共組件,組件規則遵從vue的組件規則。
template后面可以采用字符串拼接(內容少),或者是使用 `定義模板字符串。
目錄結構:
—test
——header.js //公共頭部
——index.html //頁面
——vue.js
index.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>test</title>
<!--引入vue-->
<script type="text/javascript" src="vue.js"></script>
<!--引入公共組件-->
<script type="text/javascript" src="header.js"></script>
</head>
<body style="font-size: 30px">
<div id="vue_app">
<!--自定義的組件使用-->
<common-head></common-head>
<!--頁面自有內容-->
<div style="background: #fba">我是內容</div>
</div>
</div>
<script>
//vue
app_all=new Vue({
el: "#vue_app"
})
</script>
</body>
</html>
header.js
Vue.component('common-head',{
template:`<div style="background: #baf">
<h1>這是公共組件</h1>
<h1>公共的頭部</h1>
</div>`
});
