vue cli 最新版本已经出到 4.5.8 了, 以往的一些配置,命令可能都不一样了
最新的vue 项目创建不是以往的 vue init webpack “” 这样很可能会一直卡死,所以多看官方文档是很重要的。
那么我们废话不多说,开始教大家新建项目
目录
首先更新 vue-cli
npm install @vue/cli -g
创建项目
vue create 项目名
实战
新建项目
这里一路回车
等待依赖安装完成,大概100MB 左右
创建成功
运行
npm run serve
打包发布
npm run build
以下是初始化项目常用操作
添加 vue-router
vue add router
创建 router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
// 解决重复路由报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
// 引入
Vue.use(VueRouter)
// 路由配置
const routes = [
{
path: '/',
component: ()=>import('@/views/index/index.vue')
}
]
export default new VueRouter({
mode: 'history',
routes
})
添加vuex
创建 store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
进入 App.vue
添加持久化设置,如果不加,刷新界面后 vuex 的数据会丢失
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
export default {
//进入页面时,合并本地 store
beforeCreate() {
this.$store.replaceState(Object.assign({},this.$store.state,JSON.parse(localStorage.getItem('store'))))
},
mounted() {
//离开页面时,保存 store
window.addEventListener("beforeunload",()=>{
localStorage.setItem('store',JSON.stringify(this.$store.state))
})
},
};
</script>
添加常用依赖
npm install axios less less-loader
设置路径别名 @…
创建 vue.config.js
// vue.config.js
const path = require('path');
module.exports = {
configureWebpack: {
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
}
}
},
};
创建 jsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
},
"exclude": ["node_modules", "dist"]
}
配置 main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
配置 App.vue
<template>
<div id="app">
<router-view/>
</div>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
html,body,#app{
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
</style>
封装 axios
import axios from 'axios';
const request = axios.create({
// axios 全局配置
timeout: 60 * 1000
})
// 添加请求拦截器
request.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
request.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
export default request