最近才開始學習使用 Vue,剛看到這篇文章,不懂它在說什麼,只知道在 Html 的 table 中,會將非 table 的內容,上移到 table 上方。在學習了 component 之後,終於理解它在說什麼了。
在 component 中,有幾種方式定義 template。最方便的,應該是使用 backtick (`) 來定義多行字串,不過,IE 10 不支援。我們無法強制要求使用者完全不用 IE 10,也不想辛苦的用 Javascript 的 string,因此只能選擇使用 x-template 或 DOM template。
其實,DOM template 也不是好選擇,因為在 IE 10 是不正常的,最後,只剩 x-template。關於不用 DOM template 的原因,一些測試和說明如下。
測試程式碼,如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Vue.js Template Test</title>
</head>
<body>
<div id="app">
<template-test1></template-test1>
<template-test2></template-test2>
</div>
<script type="text/javascript" src="vue_2.5.16.js"></script>
<script type="text/x-template" id="template-test1">
<div>
<h3>使用 x-template</h3>
<table border="1">
<component-test-sub
v-for="ri in 5"
v-bind:key="ri"
v-bind:ri="ri"
/>
</table>
</div>
</script>
<script>
Vue.component('template-test1', {
template: '#template-test1'
});
</script>
<!-- Template 在瀏覽器應該不會顯示,但在 IE 10 會顯示 <h3> 的 title -->
<template id="template-test2">
<div>
<h3>使用 DOM template</h3>
<table border="1">
<tr is="component-test-sub"
v-for="ri in 5"
v-bind:key="ri"
v-bind:ri="ri"
></tr>
</table>
</div>
</template>
<script>
Vue.component('template-test2', {
template: '#template-test2'
});
</script>
<script type="text/x-template" id="test-sub-template">
<tr>
<td>Row {{ ri }}</td>
</tr>
</script>
<script type="text/javascript">
Vue.component('componentTestSub', {
template: '#test-sub-template',
props: {
ri: Number // row index
}
});
new Vue({
el: '#app'
});
</script>
</body>
</html>
說明
使用 x-template,其 childNodes 只有一個,就是其中的全部內容。而使用 DOM template 時,瀏覽器會解析其內容,建立 DOM tree。因此,使用 DOM template 時,在 <table></table> 中,不能直接使用 <component-test-sub />,也不允許 self closing。
沒有留言:
張貼留言