1. 程式人生 > 其它 >html中使用引入公共元件

html中使用引入公共元件

問題描述:
整體專案採用傳統 .html 檔案搭建,vue僅作為渲染資料工具使用,需要使用的地方使用 <script> 標籤引入。
現有數個頁面,每個頁面都包含相同 header 和 footer ,希望可以把 header 和 footer 提取出來,避免太多重複程式碼。

解決辦法
公共部分寫在 .js 檔案裡,本質就是在當前頁面中寫的公共元件,元件規則遵從vue的元件規則。
template後面可以採用字串拼接(內容少),或者是使用 `定義模板字串。


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>'+
'<h1>hhhhhhh</h1>' +
'<h1>duusdfsjkdfh</h1>' +
'</div>'
});*/
Vue.component('common-head',{
template:`<div style="background: #baf">
<h1>這是公共元件</h1>
<h1>公共的頭部</h1>
</div>`
});