vue-cli使用方法:(nodejs6.0以上版本,npm3.0以上版本)
1 // install vue-cli 安裝依賴包
2 npm install –g vue-cli
3 // 使用vue-cli初始化項目
4 vue init webpack my-project
5 // install dependencies and go!
6 //進入項目目錄
7 cd my-project
8 //在項目中安裝依賴包
9 npm install
如果安裝時報如下錯誤,採用npm install [email protected] –ignore-scripts解決
10 //運行項目
11 npm run dev
2.在建立項目的過程中,有進行選擇的選項,可以選擇Y或者N,這根據自己需要所選,不影響什麼。
3.當執行完最後一步“npm run dev”的時候,就會自動在http://localhost:8080 彈出剛纔所建的項目
項目初始化完成後,講講遇到問題:
1、在index.html入口文件引入static文件中的靜態資源文件時,如果使用相對路徑並且引入路由,當第二次加載靜態資源時會報錯,找不到靜態資源,發現資源路徑錯誤,上代碼:
路由配置:
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import login from '@/components/login/login'
import firstIndex from '@/components/main/firstIndex'
import planList from '@/components/main/planList'
import listDetail from '@/components/main/listDetail'
//引起子頁面,登錄頁面
import {logins} from './loginRouter.js'
Vue.use(Router)
let routes = [{
path: '/Hello',
name: 'Hello',
component: Hello,
children:[{
path: '/firstIndex',
component: firstIndex
},{
path: '/planList',
component: planList,
children:[{
path: 'listDetail',
component: listDetail
}]
}]
}]
let others = [ {
path: '*',
component: login
}]
const scrollBehavior = (to, from, savedPosition) => {
return { x: 0, y: 0 }
}//默認回到頂部
routes = routes.concat(logins)//登錄相關
routes = routes.concat(others)//其他默認跳到登錄
export default new Router({
mode: 'history',//添加路徑中#忽略
scrollBehavior,
routes
})
入口文件錯誤引入靜態資源:
<script src="./static/js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
入口文件正確引入靜態資源:
<script src="/static/js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
將 ./ 替換成 /
./ 是指用戶所在的當前目錄(相對路徑);
/ 是指根目錄(絕對路徑,項目根目錄),也就是項目根目錄;
對於hash模式,根路徑是固定的,就是項目的根目錄,但是history模式下,以 / 開頭的嵌套路徑會被當作根路徑,所以使用“./”引入文件,就會找不到文件了,因爲文件本身就是在項目根目錄下的,並不在嵌套路徑這個目錄下,無論hash模式還是history模式,可以直接使用“/”從項目根目錄引入靜態文件。
2、初始化的項目經過自己的一點修改後怎麼也運行不出來,不是代碼層面的問題,可能是初始化項目時Use ESLint to lint your code? (Y/n) 這一步選了y,設置了eslint,代碼嚴格模式,因爲某個地方多了空格或少了空格,這時找到build文件下的webpack.base.conf.js,將下面代碼註釋就可以了:
rules: [
//初始化項目的時候Use ESLint to lint your code? (Y/n) 這一步選了y,設置了eslint
/*{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},*/
]
如果項目需要ui框架,通過npm install安裝相應的依賴包,項目中按照需要導入。