組件實(shí)現(xiàn)template和script標(biāo)簽
- 盡管在上面組件的組件注冊的方式已經(jīng)很簡單茫经,但是在template選項(xiàng)中拼接HTML的標(biāo)簽還是不符合常規(guī)的編程習(xí)慣堡距,而且HTML元素和js代碼混雜在一起造成了很大的耦合性以躯。
- 那么班缰,<strong>template和script標(biāo)簽</strong>可以幫助我們將定義在JS中的HTML模板分離出來光酣。
1.組件實(shí)現(xiàn)template標(biāo)簽
<body>
<div id="app">
<sk-component></sk-component>
</div>
<!--1.通過template,注冊一個(gè)組件-->
<template id="child">
<h1>我是自定義組件</h1>
</template>
</body>
<script src="js/vue.js"></script>
<script>
//1.實(shí)例化
Vue.component('sk-component', {
template:'#child'
});
new Vue({
el:'#app'
});
</script>
2.組件實(shí)現(xiàn)script標(biāo)簽
<body>
<div id="app">
<sk-component></sk-component>
</div>
<!--2.通過script,注冊一個(gè)組件-->
<script type="text/template" id="child">
![](images/pic1.jpeg)
</script>
</body>
<script src="js/vue.js"></script>
<script>
//1.實(shí)例化
Vue.component('sk-component', {
template:'#child'
});
new Vue({
el:'#app'
});
</script>
注意: 兩種注冊方式效果一樣厦瓢,官方建議用第一種高镐。
注意:使用
<script>
標(biāo)簽時(shí)溉旋,type指定為text/x-template,意在告訴瀏覽器這不是一段js腳本嫉髓,瀏覽器在解析HTML文檔時(shí)會忽略<script>
標(biāo)簽內(nèi)定義的內(nèi)容观腊。