在很多 vue項目中,我們使用 vue.component 來定義全局組件,緊接著用 new vue(el: ”)在每個頁面內指定一個容器元素
這種方式在很多中小規模的項目中運作的很好,在這些項目里 JavaScript 只被用來加強特定的視圖。
但擋在更復雜的項目中,或者你的前端完全由 javascript 驅動的時候,下面這些缺點將變得非常明顯:
文件擴展名為 .vue 的 sigle-file components(單文件組件)為以上所有問題提供了解決方法,并且還可以使用 webpack 或 browserify 等構建工具
這是一個文件名為 hello.vue的簡單實例
<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>
現在我們獲得:
正如我們說過的,我們可以使用預處理器來構建簡潔和功能更豐富的組件,比如 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 - 或者其他任何能夠幫助你提高生產力的預處理器。如果搭配 vue-loader 使用 Webpack,它也是把 CSS Modules 當作第一公民來對待的。
怎么看待關注點分離?
一個重要的事情值得注意,關注點分離不等于文件類型分離。
在現代 UI 開發中,我們已經發現相比于把代碼庫分離成三個大的層次并將其相互交織起來,把它們劃分為松散耦合的組件再將其組合起來更合理一些。
在一個組件里,其模板、邏輯和樣式是內部耦合的,并且把他們搭配在一起實際上使得組件更加內聚且更可維護。
即便你不喜歡單文件組件,你仍然可以把 JavaScript、CSS 分離成獨立的文件然后做到熱重載和預編譯。
<!-- my-component.vue --> <template> <div>This will be pre-compiled</div> </template> <script src="./my-component.js"></script> <style src="./my-component.css"></style>
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com