alias cli3 配置_Vue Cli3 项目配置

一、新建项目

使用 vue-cli3 构建一个初始的Vue项目:Cli3 官方文档

以下配置是我在项目中常用的,大家可自己斟酌是否需要使用!

1、环境变量

主要用于区分 开发、测试、正式环境的

(1) 在根目录新建三个文件:.env.dev .env.test .env.prod

(2) .env.dev写入

NODE_ENV = 'development'

VUE_APP_CURRENTMODE = 'test'

(3) .env.test写入

NODE_ENV = 'production'

VUE_APP_CURRENTMODE = 'test'

(4) .env.prod写入

NODE_ENV = 'production'

VUE_APP_CURRENTMODE = 'prod'

(5) 修改package.json的script

"scripts": {

"serve": "vue-cli-service serve",

"build": "vue-cli-service build",

"lint": "vue-cli-service lint"

}

修改为

"scripts": {

"serve": "vue-cli-service serve --mode dev", // 本地运行

"btest": "vue-cli-service build --mode test", // 测试环境打包

"build": "vue-cli-service build --mode prod", // 正式环境打包

"lint": "vue-cli-service lint"

}

(5) 在main.js写入

// 是否为测试环境

Vue.prototype.$istest = process.env.VUE_APP_CURRENTMODE === 'test'

console.log('当前NODE_ENV:' + process.env.NODE_ENV)

console.log('当前VUE_APP_CURRENTMODE:' + process.env.VUE_APP_CURRENTMODE)

console.log('是否为测试环境:' + Vue.prototype.$istest)

(6) 重启npm run serve,这里就不要使用vue ui启动项目了,反正我通过它启动后,无法获取process.env.VUE_APP_CURRENTMODE的值,只能通过命令行运行npm run serve启动

控制台打印结果:

image.png

2、别名设置

(1) 在vue.config.js 顶部新增

// path依赖

const path = require('path')

// 查找文件方法

const resolve = dir => {

return path.join(__dirname, dir)

}

(2) 在vue.config.js module.exports chainWebpack新增

// 别名配置

config.resolve.alias

.set('assets', resolve('src/assets'))

.set('components', resolve('src/components'))

(3) 重启npm run serve生效

若你使用的别名是图片路径的话

1、普通引入图片:需要这样使用,不能省略~

2、动态引入图片:需要这样使用,不能加上~

3、css背景图:background-image: url('~assets/img1.jpg'),不能省略~

3、全局Sass配置

在使用sass时,难免会书写一些常用的变量、函数、混合等,除了变量可以继承外,其他的只能在当前文件生效,那岂不是我需要在每一个.vue里面的

(1) 在vue.config.js module.exports 新增

// SASS配置

css: {

loaderOptions: {

sass: {

data: '@import "@/style/app.scss";'

}

}

}

(2) 在src新建style文件夹,然后在style新建app.scss

// 一些变量

$primary: #3398ff;

$success: #29cc7a;

$danger: #ee6869;

// 一些混合

@mixin primary {

color: $primary;

}

@mixin success {

color: $success;

}

@mixin danger {

color: $danger;

}

// 一些循环

@for $i from 12 through 30 {

.f#{$i} {

font-size: 1px * $i !important;

}

}

(3) 重启npm run serve,然后在.vue使用

.div1 {

color: $primary; // 使用scss变量

}

.div2 {

@include success; // 使用scss混合

}

在template中使用

使用scss循环生成的类名(.f12 ~ .f30)f代表:font-size

4、全局默认Css配置

在public/index.html里面的

新增

5、基础组件的自动化全局注册

(1) 在src/components新建global.js

import Vue from 'vue'

// 找到components文件夹下以.vue命名的文件

const RC = require.context('.', true, /\.vue$/)

RC.keys().forEach(fileName => {

const componentConfig = RC(fileName)

// 因为得到的filename格式是: './baseButton.vue', 所以这里我们去掉头和尾,只保留真正的文件名

let componentName = fileName.replace(/^\.\//, '').replace(/\.\w+$/, '')

let index = componentName.indexOf('/')

if (index !== -1) componentName = componentName.substr(index + 1)

Vue.component(componentName, componentConfig.default || componentConfig)

})

(2) 在main.js里面引入

import './components/global'

(3) 不用重启,直接在.vue里面template写组件即可

6、Vuex配置

(1) 安装依赖:cnpm i -S vuex-persistedstate

vuex在刷新后会重新更新状态,但是有时候我们并不希望如此。例如全局相关的,如登录状态、token、以及一些不常更新的状态等,我们更希望能够固化到本地,减少无用的接口访问,以及更佳的用户体验。

vuex-persistedstate:即可解决,可将值放到 sessionStorage或localStorage中

(2) 在src/store.js 修改

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({

state: {},

mutations: {},

actions: {}

})

修改为

import Vue from 'vue'

import Vuex from 'vuex'

import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({

state: {

// token信息

token: ''

},

mutations: {

save(state, [key, data, local = false]) {

if (!key) throw new Error('mutations save need key!')

const keyPath = key.split('.')

const len = keyPath.length

const lastKey = keyPath.pop()

let needSave = state

for (let i = 0; i < len - 1; i++) {

needSave = needSave[keyPath[i]]

}

if (!needSave.hasOwnProperty(lastKey)) {

throw new Error(`【${key}】 Error Key: ${lastKey}`)

}

needSave[lastKey] = data

if (local) {

window.sessionStorage.setItem(key, JSON.stringify(data))

}

}

},

plugins: [createPersistedState({ storage: window.sessionStorage })]

})

(3) 无需重启,直接刷新页面即可成功使用vuex

(4) 在.vue中,执行

this.$store.commit('save', ['token', 'token2'])

即可改变 state.token 的值

7、Vue-Router配置

(1) 安装依赖:cnpm i -S vue-router-auto

vue-router-auto:将项目文件自动转为相应的路由配置

(2) 在src/route.js修改

import Vue from 'vue'

import Router from 'vue-router'

import Home from './views/Home.vue'

Vue.use(Router)

export default new Router({

mode: 'history',

base: process.env.BASE_URL,

routes: [

{

path: '/',

name: 'home',

component: Home

},

{

path: '/about',

name: 'about',

// route level code-splitting

// this generates a separate chunk (about.[hash].js) for this route

// which is lazy-loaded when the route is visited.

component: () =>

import(/* webpackChunkName: "about" */ './views/About.vue')

}

]

})

修改为

import Vue from 'vue'

import Router from 'vue-router'

import autoRouter from 'vue-router-auto' // 引入依赖

if (!window.VueRouter) Vue.use(Router)

// 自动生成路由数据

const routes = autoRouter({

redirect: '/home',

rc: require.context('@/views', true, /\.vue$/)

})

// 将生成的路由数据,挂载到 new Router

export default new Router({

mode: 'history',

base: process.env.BASE_URL,

routes

})

8、api请求配置

(1) 安装依赖:cnpm i -S axios hzq-axios

hzq-axios:对 axios 请求的二次封装,封装成 Vue 插件 this.$api ,并支持Axios请求、响应拦截

(2) 在src下,新建apiurl文件夹,在apiurl文件夹下新建index.js

export default [

{

name: 'GetImageCaptcha',

url: '/Captcha/GetImageCaptcha'

}

]

(3) 在main.js里引入并使用:

import hzqAxios from 'hzq-axios'

Vue.use(hzqAxios, require.context('@/apiurl', true, /\.js$/), {

baseURL: '/api',

// 请求拦截之前

beforeRequest(config) {

console.log(config)

return config

},

// 接口响应成功事件

respSuccess(res) {

console.log(res)

},

// 接口响应失败事件

respError(e) {

console.log(e)

}

})

(4) 在vue.config.js module.exports 新增devServer的设置

devServer: {

// 代理

proxy: {

'/giftapi': {

target: 'http://***.***.com',

ws: true,

changeOrigin: true

}

}

}

(5) 重启npm run serve生效

(6) 在.vue中,这样使用

this.$api.GetImageCaptcha().then(res => {

if (res.code === 1) {

console.log(res.data)

}

})

9、Vue全局方法、变量配置

(1) 安装依赖:cnpm i -S hzq-tool

hzq-tool:基于 Vue 对一些常用的工具函数进行封装,通过 this.$tool 调用

(2) 在main.js引入并使用

import hzqTool from 'hzq-tool'

Vue.use(hzqTool)

(3) 无需重启,在.vue里面使用

const b = { name: '12' }

const a = this.$tool.copy(b) // 深拷贝方法

this.$setItem('id', '123456') // 往sessionStorage存入数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值