Vuejs 單檔案組件執行個體詳解,vuejs組件執行個體詳解

來源:互聯網
上載者:User

Vuejs 單檔案組件執行個體詳解,vuejs組件執行個體詳解

在之前的執行個體中,我們都是通過 Vue.component 或者 components 屬性的方式來定義組件,這種方式在很多中小規模的項目中還好,但在複雜的項目中,下面這些缺點就非常明顯了:

字串模板:缺乏高亮,書寫麻煩,特別是 HTML 多行的時候,雖然可以將模板寫在 html 檔案中,但是侵入性太強,不利於組件解耦分離。

不支援CSS:意味著當 HTML 和 JavaScript 組件化時,CSS明顯被遺漏了

沒有構建步驟:限制只能使用 HTML 和 ES5 JavaScript,而不能使用前置處理器。

Vuejs 提供的副檔名為 .vue 的 單檔案組件 為以上所有問題提供瞭解決方案。

初識單檔案組件

還是利用工欲善其事必先利其器 中的源碼,在 src 目錄下建立 hello.vue 檔案,內容如下:

<template> <h2>{{ msg }}</h2></template><script>export default {data () {return {msg:'Hello Vue.js 單檔案組件~'}}}</script><style>h2 {color: green;}</style>

然後在 app.js 中引入使用:

// ES6 引入模組文法import Vue from 'vue';import hello from './hello.vue';new Vue({ el: "#app", template: '<hello/>', components: {  hello }});

此時項目是沒法啟動並執行,因為 .vue 檔案 webpack 是沒法是別的,它需要對應的 vue-loader 來處理才行,而且細心的朋友會發現 hello.vue 中用到了 ES6 文法,此時就需要用到相應的文法轉化 loader 將 ES6 轉化成主流瀏覽器安全色的 ES5 文法,這裡就需要用到官方推薦的 babel 工具了。先安裝需要的 loader :

# hello.vue 檔案中使用了 css,所以需要 css-loader 來處理,vue-loader 會自動調用npm install vue-loader css-loader babel-loader babel-core babel-preset-env --save-dev

有的人疑惑只是使用 babel-loader 為什麼還需要安裝後面這麼多工具呢,這是因為很多工具都是獨立的, loader 只是為了配合 webpack 使用的橋樑,而這裡 babel-core 和 babel-preset-env 才是實現 ES6 到 ES5 的核心。

我們再修改 webpack.config.js 配置如下:

module.exports = { // ... module: {  // 這裡用來配置處理不同尾碼檔案所使用的loader  rules: [   {    test: /.vue$/,    loader: 'vue-loader'   },   {    test: /.js$/,    loader: 'babel-loader'   }  ] }}

對於 babel 的配置,我們還需在項目根目錄下剛建立 .babelrc 檔案來配置 Babel presets 和 其他相關外掛程式,內容如下:

{ "presets": [ "env" ]}

但是雖然雖然都配置好了,項目還是還是會報錯,報如下錯誤:

ERROR in ./src/hello.vueModule build failed: Error: Cannot find module 'vue-template-compiler'

有人就不高興了,明明是按照官方提示安裝了依賴,並正確的進行配置,為什麼還是會報錯呢?遇到錯誤不要怕,先閱讀下錯誤是什麼,很容易發現,是因為 Cannot find module 'vue-template-compiler' ,這是因為 vue-loader 在處理 .vue 檔案時,還需要依賴 vue-template-compiler 工具來處理。

剛開始我不知道官方為什麼沒有直接告訴使用者需要安裝這個依賴,通過閱讀 vue-loader 才明白其 package.json 檔案中是將 vue-template-compiler 和 css-loader 作為 peerDependencies ,而 peerDependencies 在安裝的時候,並不會自動安裝(npm@3.0+),只會給出相關警告,所以這個需要我們手動安裝的,當然在 .vue 檔案中如果需要寫 CSS,也必須用到 css-loader ,這個也是在 peerDependencies 中。相關討論: https://github.com/vuejs/vue-loader/issues/1158

知道問題了,直接安裝下就可以了:

npm install vue-template-compiler css-loader --save-dev

再次運行項目,頁面中出現了我們的內容,並沒報錯,ok,大功告成~

使用前置處理器

我們已經學會在 .vue 中寫 css 了,那麼如果使用 sass 前置處理器呢?首先安裝上篇文章中提到的模組:

npm install sass-loader node-sass --save-dev

配置只需兩步:

修改 webpack.config.js 中 vue-loader 配置

module.exports = { // ... module: {  // 這裡用來配置處理不同尾碼檔案所使用的loader  rules: [   {    test: /.vue$/,    loader: 'vue-loader',    options: {     loaders: {      // 這裡也可以使用連寫方式,但是不利於自訂話參數配置      // scss: 'vue-style-loader!css-loader!sass-loader'      scss: [       {        loader: 'vue-style-loader'       },       {        loader: 'css-loader'       },       {        loader: 'sass-loader'       }      ]     }    }   },   // ...  ] }}

給 .vue 檔案中的 style 標籤,添加 lang="scss" 屬性。

配置完後,就可以再 .vue 檔案中,愉快地編寫 sass 文法了。

載入全域設定檔案

實際開發中,我們在編寫 sass 檔案時,經常會將全域的 scss 變數提取出來,放到一個單獨的檔案中,但是這樣就有個問題,每個需要用到的組件,都需要手動 @import './styles/_var.scss' 進來,非常不友好。外掛程式 sass-resources-loader 就很好地幫我們解決這個問題,先安裝一下:

npm install sass-resources-loader --save-dev

然後修改 webpack.config.js 檔案中 vue-loader 相關配置:

// ...{ test: /.vue$/, loader: 'vue-loader', options: {  loaders: {   scss: [    {     loader: 'vue-style-loader'    },    {     loader: 'css-loader'    },    {     loader: 'sass-loader'    },    // 看這裡,看這裡,看這裡    {     loader: 'sass-resources-loader',     options: {      // 這裡的resources 屬性是個數組,可以放多個想全域引用的檔案      resources: [resolve('./src/styles/_var.scss')]     }    }   ]  } }}// ...

配置就完成了,我們再來測試下。

在 src 目錄下分別建立 hello1.vue 和 hello2.vue 檔案:

<!-- hello1.vue --><template> <h1>{{ msg }}</h1></template><script>export default {name:'hello1',data () {return {msg:'Hello Vue.js 單檔案組件~'}}}</script><stylelang="scss">h1 {color: $green;}</style><!-- hello2.vue --><template> <h1>{{ msg }}</h1></template><script>export default {name:'hello2',data () {return {msg:'Hello Vue.js 單檔案組件~'}}}</script><stylelang="scss">h1 {color: $red;}</style>

然後建立一個 styles 目錄,並在其中建立存放全域變數的檔案 _var.scss :

$green: rgb(41, 209, 41);$red: rgb(177, 28, 28);

接下來,在 app.js 中引用兩個組件:

import Vue from 'vue';import hello1 from './hello1.vue';import hello2 from './hello2.vue';new Vue({ el: "#app", template: '<div><hello1/><hello2/></div>', components: {  hello1,  hello2 }});

重新運行項目就可以了。

有範圍的 style

單檔案組件中為我們提供了一個非常便利的功能,就是當 style 標籤添加 scoped 屬性時,標籤內的樣式將只作用於當前組件中的元素。

接著上面的例子,運行後會發現 hello1.vue 中的 h1 顏色並不是想要的 $green 色,而是被 hello2.vue 中的樣式覆蓋了。於是分別在 hello1.vue 和 hello2.vue 的 style 標籤上添加 scoped 屬性,如下:

<!-- hello1.vue --><stylelang="scss"scoped>h1 {color: $green;}</style><!-- hello2.vue --><stylelang="scss"scoped>h1 {color: $red;}</style>

這樣一來我們的兩個 h1 標籤顏色都顯示正常了。

自訂塊

在編寫某些開源組件時,有時候我們需要同時維護多個組件和組件說明,但是每次修改就要同時修改 .vue 和 .md 檔案,相當麻煩。 .vue 檔案的 自訂語言塊 功能,就允許我們將 markdown 說明同時寫進 .vue 檔案中,然後通過外掛程式將其說明部分單獨提取到相應的 .md 檔案中,這樣就可以同時維護說明文檔和組件功能了。

比如我們將 hello1.vue 檔案修改如下:

<docs> # 標題  這是標題內容,[倉庫地址](https://github.com/yugasun/You-Dont-Know-Vuejs) ## 子標題  這是子標題內容</docs><template> <h1>{{ msg }}</h1></template><script>export default {name:'hello1',data () {return {msg:'Hello Vue.js 單檔案組件~'}}}</script><stylelang="scss"scoped>h1 {color: $green;}</style>

然後修改 webpack.config.js 配置:

const path = require('path');// 引入相關外掛程式const ExtractTextPlugin = require('extract-text-webpack-plugin');function resolve(dir){ return path.resolve(__dirname, dir);}module.exports = { // 入口檔案 entry: './src/app.js', // 編譯輸出檔案 output: {  path: resolve('./'),  filename: 'build.js' }, resolve: {  alias: {   // 因為我們這裡用的是 require 引入方式,所以應該使用vue.common.js/vue.js/vue.min.js   'vue$': 'vue/dist/vue.common.js'  } }, devServer: {  // 這裡定義 webpack-dev-server 開啟的web服務的根目錄  contentBase: resolve('./') }, module: {  // 這裡用來配置處理不同尾碼檔案所使用的loader  rules: [   {    test: /.vue$/,    loader: 'vue-loader',    options: {     loaders: {      scss: [       {        loader: 'vue-style-loader'       },       {        loader: 'css-loader'       },       {        loader: 'sass-loader'       },       {        loader: 'sass-resources-loader',        options: {         resources: [resolve('./src/styles/_var.scss')]        }       }      ],      docs: ExtractTextPlugin.extract('raw-loader')     }    }   },   {    test: /.js$/,    loader: 'babel-loader'   }  ] }, plugins: [  new ExtractTextPlugin('docs.md') ]}

這裡用到了 extract-text-webpack-plugin 匯出 text 外掛程式,和 raw-loader ,分別都安裝下就行。

然後運行構建命令 npm run build ,等運行結束,根目錄下會同時產生一個 docs.md 檔案,這就是我們想編寫的說明文檔。

點擊查看源碼:https://github.com/yugasun/You-Dont-Know-Vuejs/tree/master/chapter2/2

總結

以上所述是小編給大家介紹的Vuejs 單檔案組件執行個體詳解,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.