vue中的單文件組件是以.vue擴展名結尾的文件,在這個文件中封裝了html、js、css的代碼,它自身是一個獨立的組件,因此成爲單文件組件;css
因爲.vue封裝了html、js、css的代碼,因此它由如下幾部分組成;html
<template> html </template>前端
<script> js </script>vue
<style> css </style>java
若是使用.vue文件,須要使用指定加載器,不然瀏覽器是不能解析的。加載.vue文件的加載器是 vue-loader; 同理,一個項目中還須要html、css等,因此也要用到其對應的加載器 例:html-loader、css-loader… vue-loader是基於webpack的,要在webpack中進行配置,因此還要配置webpack;node
javaScript應用的靜態模塊打包器;把前端各類資源做爲模塊處理、使用、打包;webpack
官網: 點擊前往es6
基於webpack的單文件組件項目基本結構web
一、index.html 基本頁面npm
二、App.vue vue根組件
三、 main.js 入口文件
四、package.json 項目配置文件
五、webpack.config.js webpack配置文件
六、 .babelrc babel配置文件,babel能夠將es6轉成es5
經過管理員窗口使用指令生成package.json 項目配置文件
因爲在開發的過程當中須要使用.vue文件
基於webpack的單文件組件項目須要安裝如下依賴
webpack
Loader
template
babel
安裝完package.json的最終效果:
附:須要按照順序一個一個進行安裝,預防後面的依賴前面的包
main.js
import Vue from 'vue'//引入內置模塊 import App from './app.vue'//引入自定義模塊 new Vue({ el:'#app', //使用render渲染 render:function(r){ return r(App); } })
index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> </body> </html>
app.vue
<template> <h2> 歡迎來到perfect*的博客園!!!</h2> </template> <script> </script> <style> </style>
webpack.config.js
const VueLoaderPlugin=require('vue-loader/lib/plugin'); module.exports={ //1配置入口文件 entry:'./main.js', //2配置出口 output:{ path:__dirname, filename:'build.js' }, //3配置loader module:{ rules:[ { //.vue test:/\.vue$/, loader:'vue-loader' }, { //js test:/\.js$/, loader:'babel-loader', exclude:'/node_modules/'//排除該目錄 }, { //css test:/\.css$/, use:[ 'vue-style-loader', 'css-loader' ] } ] }, //4配置插件 plugins:[ new VueLoaderPlugin() ], //5設置模式 mode:'development'//開發模式 }
以後在index.html中的加入:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> </body> <script src="build.js"></script><!--放在head標籤之間找不到項目的掛載點--> </html>
自定義文件.babelrc
{ "presets":[ [ "env", { "moudle":false } ] ] }
package.json中加入:
{ "name": "simple-file", "version": "1.0.0", "description": "", "main": "main.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev":"webpack-dev-server --open --hot --port8088 --config webpack.config.js --mode development" },
在管理員窗口輸入npm run dev 進行運行該項目:
最終效果:
能夠在app.vue中添加js代碼,在控制檯打印出內容,以及修改其樣式
app..vue
<template> <h2> 歡迎來到perfect*的博客園!!!</h2> </template> <script> console.log('歡迎來到perfect*的博客園') </script> <style> h2{ color: red; } </style>