在很多 vue項(xiàng)目中,我們使用 vue.component 來定義全局組件,緊接著用 new vue(el: ”)在每個(gè)頁面內(nèi)指定一個(gè)容器元素
這種方式在很多中小規(guī)模的項(xiàng)目中運(yùn)作的很好,在這些項(xiàng)目里 JavaScript 只被用來加強(qiáng)特定的視圖。
但擋在更復(fù)雜的項(xiàng)目中,或者你的前端完全由 javascript 驅(qū)動(dòng)的時(shí)候,下面這些缺點(diǎn)將變得非常明顯:
文件擴(kuò)展名為 .vue 的 sigle-file components(單文件組件)為以上所有問題提供了解決方法,并且還可以使用 webpack 或 browserify 等構(gòu)建工具
這是一個(gè)文件名為 hello.vue的簡單實(shí)例
<template> <p> {{ gretting}} world! </p> </template> <script> module.exports = { data: function(){ return { greeting: 'hello' } } } </script> <style scoped> p { font-size: 2em; text-algin: center } </style>
現(xiàn)在我們獲得:
正如我們說過的,我們可以使用預(yù)處理器來構(gòu)建簡潔和功能更豐富的組件,比如 pug,babel,和 stylus
<template lang="jade"> div p {{greeting}} world! other-component </template> <script> import default{ data(){ return{ greeting:'hello' } }, components: { OtherComponent } } </script> <style lang='stylus' scoped> p font-size: 2em; text-align: center </style>
這些特定的語言只是例子,你可以只是簡單地使用 Babel,TypeScript,SCSS,PostCSS - 或者其他任何能夠幫助你提高生產(chǎn)力的預(yù)處理器。如果搭配 vue-loader 使用 Webpack,它也是把 CSS Modules 當(dāng)作第一公民來對(duì)待的。
怎么看待關(guān)注點(diǎn)分離?
一個(gè)重要的事情值得注意,關(guān)注點(diǎn)分離不等于文件類型分離。
在現(xiàn)代 UI 開發(fā)中,我們已經(jīng)發(fā)現(xiàn)相比于把代碼庫分離成三個(gè)大的層次并將其相互交織起來,把它們劃分為松散耦合的組件再將其組合起來更合理一些。
在一個(gè)組件里,其模板、邏輯和樣式是內(nèi)部耦合的,并且把他們搭配在一起實(shí)際上使得組件更加內(nèi)聚且更可維護(hù)。
即便你不喜歡單文件組件,你仍然可以把 JavaScript、CSS 分離成獨(dú)立的文件然后做到熱重載和預(yù)編譯。
<!-- my-component.vue --> <template> <div>This will be pre-compiled</div> </template> <script src="./my-component.js"></script> <style src="./my-component.css"></style>
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com