前端組件化開發(fā)已經(jīng)是一個老生常談的話題了,組件化讓我們的開發(fā)效率以及維護成本帶來了質(zhì)的提升。
當(dāng)然因為現(xiàn)在的系統(tǒng)越來越復(fù)雜龐大,所以開發(fā)與維護成本就變得必須要考慮的問題,因此滋生出了目前的三大前端框架 Vue、Angular、React。
那今天我們就來看看 Vue 中有哪些定義組件模版的方式以及他們之間的一些差別。
字符串形式
Vue 最簡單直接的一種定義組件模版的方式,但是方式寫起來很不友好,就像我們以前拼接 HTML 元素是一樣的,很痛苦,所以我們并不常用
Vue.component("my-button", { data: function () { return { label: "是兄弟就來砍我" } }, template: "<button>{{label}}</button>" });
模版字面量
模版字面量 ES6 語法,與字符串不同的是,我們可以進行多行書寫,相對單純字符串有很大優(yōu)勢,體驗更優(yōu),但是可能瀏覽器兼容性會存在問題,需要進行轉(zhuǎn)譯為 ES5 語法。
Vue.component("my-content", { data: function () { return { label: "是兄弟就來砍我", content: "刀刀暴擊" } }, template: ` <div> <button>{{ label }}</button> <span>{{ content }}</span> </div> ` });
內(nèi)聯(lián)模版(inline-template)
與 「X-template」模版定義方式被稱為模版定義的替代品,把內(nèi)容定義在組件標(biāo)簽元素的內(nèi)部,而不是作為 slot 內(nèi)容分發(fā),方式比較靈活,但是給讓我們組件的模版與其他屬性分離開。
<my-label inline-template> <span>{{label}}</span> </my-label> Vue.component('my-label', { data: function () { return { label: "趕緊上車吧,兄die" } } })
X-template
定義一個 <script> 標(biāo)簽,標(biāo)記 text/x-template
類型,通過 id 鏈接。
<script type="text/x-template" id="label-template"> <span>{{label}}</span> </script> Vue.component('my-label', { template: "#label-template", data: function () { return { label: "趕緊上車吧,兄die" } } })
渲染函數(shù)
渲染函數(shù)需要 JavaScript 完全的編程能力,而且比模版更接近編譯,但需要我們非常熟悉 Vue的實例屬性,也會更加的抽象。像 v-if v-for
指令就可以用 JavaScript 語法輕松實現(xiàn)。
Vue.component('my-label', { data: function () { return { items: ['來就送!', '來就送!', '來就送!'] } }, render: function (createElement) { if (this.items.length) { return createElement('ul', this.items.map(function (item) { return createElement('li', item) })) } else { return createElement('p', '活動結(jié)束') } } })
JSX
相比渲染函數(shù)的抽象而言,JSX 比較容易一些,對于熟悉 React 的同學(xué)是比較友好的。
Vue.component('my-label', { data: function () { return { label: ["活動結(jié)束"] } }, render(){ return <div>{this.label}</div> } })
單文件組件
使用構(gòu)建工具 cli 創(chuàng)建項目,綜合來看單文件組件應(yīng)該是最好的定義組件的方式,而且不會帶來額外的模版語法的學(xué)習(xí)成本。
<template> <div> <ul> <li v-for="(item, index) in items" :key="index">{{item}}</li> </ul> </div> </template> <script> export default { data() { return { items: ["我砍", "我砍", "我砍"] }; } }; </script>
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com