基於vue-cli(vue腳手架)搭建Vue項目總結
一、運行環境
node (v8.12.0) (官網下載安裝)+ npm(Node.js的包管理工具) (6.4.1) + Vue(構建用戶界面的漸進式框架)(2.9.6) + Intellij IDEA
在之前已安裝過node 、npm(npm install -g npm),通過node -v 、 npm -v 查看已安裝的版本號,驗證是否安裝成功。下面主要是安裝、配置Vue相關的開發環境。
1、安裝腳手架vue-cli
全局安裝vue-cli,安裝完成後,可通過vue -V查看vue的版本號。
sudo npm install -g vue-cli
2、Intellij idea安裝依賴插件
Preferences - > Plugins 下搜索Vue.js, 安裝對Vue的支持。
二、實例總結
1、快速創建vue項目
# vue init webpack testvue
備註:
1.Vue build: # 打包方式
2.Install vue-router? # 安裝vue-router, 項目中會用到,Y需要安裝
3.Use ESLint to lint your code? # 是否需要js語法檢測
4.Pick an ESLint preset
5.Set up unit tests # 是否安裝單元測試工具
6.Setup e2e tests with Nightwatch? # 是否需要端到端測試工具
7.Should we run `npm install` for you after the project has been created? (recommended) # 安裝依賴,如果選擇No, 也可通過cnpm i 安裝
2、第一個頁面
2.1 目錄結構
實際在Intellij idea中會提示js錯誤,默認javascript的版本不夠導致。 在Preferences | Languages & Frameworks | JavaScript 下修改JavaScript language version即可。
備註:
1.build: 構建腳本目錄
2.config: 項目配置
3.node_modules: npm加載的項目依賴模塊
4.src: 開發的目錄
1)assets:資源目錄,放置一些圖片或者公共js、公共css,會被webpack構建;
2)components:組件目錄;
3)router:前端路由,需要配置的路由路徑寫在index.js裏面;
4)App.vue:根組件;
5)main.js:入口js文件;
5.static: 靜態資源目錄
6.index.html: 首頁入口文件
7.package.json: npm包配置文件
8.README.md: 說明文檔
9. .XXX文件:一些配置文件,包括語法配置,git配置等
2.2 實踐
1)components下新建Test.vue
template:寫html等;
script:js
style:樣式
<template>
<div>
<h1>hi, {{msg}} ! </h1>
</div>
</template>
<script>
export default {
name: 'Test',
data () {
return {
msg: 'Test first'
}
}
}
</script>
<style scoped>
</style>
2)在router/index.js中配置路由路徑
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Test from '@/components/Test' # import
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
}, {
path: '/test', # /test跳轉test.vue
name: 'Test',
component: Test
}
],
mode: 'history'
})
3)在HelloWord主頁下加入跳轉Test
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>Essential Links</h2>
<p><router-link to="/test">next-></router-link></p> # router-link
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
2.3、run
npm run dev # serve with hot reload at localhost:8080
編譯成功後訪問http://localhost:8080可查看效果:
運行結果:
2.4 其他配置:
config/index.js: 配置端口號(避免衝突)、或者自動打開瀏覽器