最近又再重複的温习了 Vue 的 component,希望能重新帮自己整理思绪
component 俗称元件,在网页我们每一个区块内容都可以封装成一个独立的元件,而元件还可以再包覆其他元件,有点类似 HTML 的标籤还可以再包覆标籤的概念是一样的。
建立 component
而在 Vue 里面,建立 component 有分为区域性跟全域性:
区域性的建立如下:
const child = { teamplate: '', props: [],}const app = new Vue({ el: '#app', data: {}, components: { 'my-component': child }});
而全域性,则是採用了 Vue.component() 的方法:
Vue.component('my-component', { template: '', props: [],});
而两者的差别在于,当今天有两个 Vue 实体时,全域性的 component 可以被重複利用,但区域性的 component 则无法,下面採用了全域的 component 建立,所以在 app2 内 my-conponent 是可以被运作的:
<div id="app"> <my-component></my-component></div><div id="app2"> <my-component></my-component></div><script> Vue.component('my-component', { template: '<div>Hello</div>' }); const app = new Vue({ el: '#app', }); const app2 = new Vue({ el: '#app2', });</script>
如果改成区域性:
<script> const child = { template: '<div>Hello</div>' }; const app = new Vue({ el: '#app', components: { 'my-component': child } }); const app2 = new Vue({ el: '#app2', });</script>
我们仅在 app 内的 components 调用了 child 这个变数,并没有也在 app2 内也调用,所以此时 app2 内的 my-component 是会出现错误的通知
data function return
接着如果我们建立 component 时,要使用 data 这个方法时,需使用 function return,这是避免跟 Vue 实体的资料冲突:
Vue.component('myComponent', { template: '<button @click="counter ++"></button>'});const app = new Vue({ el: '#app', data: { counter: 0, }});
如果这样写,Vue.component() 内并无使用 data function return,当 button 被点击时,是直接更改 Vue 实体的资料的,避免这样的情形,所以要改成如下:
Vue.component('myComponent', { template: '<button @click="counter ++"></button>', data: function(){ return { counter: 0 } }});
x-template 封装 HTML
前面我们建立 component 时,所使用的 template 属性,都是直接赋予 HTML 内容,但今天如果 HTML 内容太多的时候,就会显得画面太乱太过于複杂,所以这个时候我们就可以使用 x-template 来封装 HTML 的内容,并且我们直接用 id 呼叫即可:
<script type="text/x-template" id="my-component"> <div class="card"> ... </div></script><script> Vue.component('my-component', { template: '#my-component' });</script>
在 template 呼叫 x-template 的 id 即可
这里要注意一个小重点,x-template 内最外层仅只能有一个节点