目录
前提
你需要安装好vue-cli脚手架
注意:该文章只针对与vue-cli版本为4.5.15
查看自己vue版本 vue -V
如果版本高于4.5.15需要降低版本
输入一下代码:
npm install -g @vue/[email protected]
一、创建项目
1.新建一个文件夹 (不能为中文),输入cmd 打开该文件夹
打开效果显示:
2.输入 vue create . 回车
vue create .
3.回车后提示 : 是否在此目录创建项目 输入 yes后回车继续
(如图)
4.选择预设 按方向键切换到最后一个 手动选择功能 然后回车(如图)
5.按方向键进行上下移动,按空格选中,选择好后回车 (如图)
6.选择vue版本 选3.x 然后回车 (如图)
7.之后的提示全部选 no (如图)回车
8.选择css预处理器 这里选择less(如图)回车
9.单元测试方案 ,选择默认的第一个(如图)
10.选择配置的保存位置 选第二个(如图)
11.是否保存为预设, y 保存 ;n 不保存。 这里我们按y保存一下以便于以后使用 (如图)
12.输入预设的名字, 回车等待下载(如图)
13.等待下载(如图)
14.下载完成后(如图)
15.下载完毕后 输入 npm run serve
,回车启动项目
npm run serve
二、less的px转rem
1.移动端适配
(1).项目启动后 在命令行中按ctrl + c 停止运行项目
(2).命令行输入以下代码 下载'lib-flexible' 'postcss-px2rem-exclude' 两个插件
npm i lib-flexible postcss-px2rem-exclude -save
(3).下载完成后 用vscode打开项目 在入口文件 main.ts 中 引入 lib-flexible
import 'lib-flexible'
2.px转rem
(1).在项目根目录下创建 vue.config.js 并在里面配置
// vue.config.js
module.exports = {
css:{
loaderOptions:{
postcss:{
plugins:[
require('postcss-px2rem-exclude')({
remUnit:75,
exclude:/node_modules/
}),//换算的基数
]
}
}
},
}
(2).打开package.json文件 ,添加:
"postcss":{
"plugins":{
"autoprefixed":{}
}
}
(3).配置完成后, 重启项目
三、配置反向代理 + axios
1.反向代理3
打开vue.config.js配置文件,在module.exports 中添加以下代码
devServer: {
proxy: {
// 配置跨域
'/api': {
target: 'http://....................', //这里是后端接口地址
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
open: true //启动项目自动打开浏览器
}
2.配置axios
(1).下载axios:
npm install axios --save
(2).在src目录下创建api文件夹 , 文件夹内创建 index.ts 和 request.ts 两个文件
request.ts中:
import axios from "axios";
export const Service = axios.create({
timeout: 8000, //延迟时间
method: 'POST',
headers: {
"content-Type": "application/x-www-form-urlencoded",
"pc-token": "4a82b23dbbf3b23fd8aa291076e660ec", //后端提供
}
})
// 请求拦截
Service.interceptors.request.use(config => {
return config
})
// 响应拦截
Service.interceptors.response.use(response => {
return response.data
}, err => {
console.log(err)
})
index.ts中:
import { Service } from "./request";
interface searchConfig {
page: number | string
mod: string
}
interface getConfig {
page: number | string
}
// 搜索接口
export function searchCar(config: searchConfig) {
const params = new URLSearchParams()
params.append('page', config.page as string);
params.append('mod', config.mod);
return Service({
url: "./api/oldcar/searchCar",
data: params
})
}
// 列表接口
export function getCarList(config: getConfig) {
const params = new URLSearchParams()
params.append('page', config.page as string)
return Service({
url: "/api/oldcar/getCarList",
data: params
})
}
3.在view/about中测试:
<template>
<div class="about">
<h1>This is an about page</h1>
<button @click="getData">获取数据</button>
</div>
</template>
<script lang="ts">
import { getCarList } from "../api"; //引用
import { defineComponent, onMounted } from "vue";
export default defineComponent({
setup() {
const getData = async function () {
console.log(await getCarList({ page: 1 }));
};
onMounted(async() => {
console.log(await getCarList({ page: 1 }));
});
return {
getData,
};
},
});
</script>
点击按钮获取数据