基于脚手架创建前端工程
环境要求
node.js:前端项目的运行环境(相当于Java的运行环境JDK)
npm:JS的包管理工具/器
Vue CLI:基于Vue进行快速开发的完整系统,实现交互式的项目脚手架
创建Vue基础项目代码:vue ui
查看node和npm的版本号
node -v
npm -v
安装Vue CLI命令
npm i @vue/cli -g
项目结构
node_modules:当前项目依赖的js包
assets:静态资源存放目录
components:公共组件存放目录
App.vue:项目的主组件,页面的入口文件
main.js:整个项目的入口文件
package.json:项目的配置信息、依赖包管理
vue.config.js:vue-cli配置文件
启动Vue前端项目
若package.json文件中的scripts代码为如下:
"scripts":{
"serve":"vue-cli-service serve",
"build":"vue-cli-service build",
"lint":"vue-cli-service lint"
}
则运行npm run serve
若package.json文件中的scripts代码为如下:
scripts":{
"dev":"vue-cli-service serve",
"build":"vue-cli-service build",
"lint":"vue-cli-service lint"
}
则运行npm run dev
直接使用npm脚本
停止前端项目
Ctrl + C
修改前端服务的端口号
在vue.config.js中配置前端服务端口号:
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({transpileDependencies: true,devServer: {port: 7070 }
})
Vue文件组成
Vue 的组件文件以 .vue 结尾,每个组件由三部分组成:
template、style、script
<template><div></div>
</template>
<script>export default {data() {return { name: 'XXX', };},methods: {Save(){alert(this.name)}}};
</script>
<style></style>
Vue基本使用
文本插值
作用:用来绑定 data 方法返回的对象属性
用法:{{}}(其中也可以使用三目运算等)
属性绑定
作用:为标签的属性绑定 data 方法中返回的属性(单向绑定)
用法:v-bind:xxx,简写为 :xxx
事件绑定
作用:为元素绑定对应的事件
用法:v-on:xxx,简写为 @xxx
双向绑定
作用:表单输入项和 data 方法中的属性进行绑定,任意一方改变都会同步给另一方
用法:v-model
条件渲染
作用:根据表达式的值来动态渲染页面元素
用法:v-if、v-else、v-else-if
还有一个v-show
axios
概念:Axios 是一个基于 promise 的 网络请求库,作用于浏览器和 node.js 中,发送各种方式的http请求。
安装命令
npm install axios
导入命令
import axios from ‘axios’
axios 的主要 API 列表
请求:get和post
axios 的post、get 方法示例
axios.post('/api/XXX/XX',{username:'admin',password: '123456'}).then(res => {console.log(res.data)}).catch(error => {console.log(error.response)}),
axios.get('/api/XX/XX',{headers: {token: ‘xxx.yyy.zzz’}})
axios 统一使用方式:axios(config)
{// `url` 是用于请求的服务器 URLurl: '/user',// `method` 是创建请求时使用的方法method: 'get', // 默认值// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URLbaseURL: 'https://some-domain.com/api/',// `transformRequest` 允许在向服务器发送前,修改请求数据// 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法// 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream// 你可以修改请求头。transformRequest: [function (data, headers) {// 对发送的 data 进行任意转换处理return data;}],// `transformResponse` 在传递给 then/catch 前,允许修改响应数据transformResponse: [function (data) {// 对接收的 data 进行任意转换处理return data;}],// 自定义请求头headers: {'X-Requested-With': 'XMLHttpRequest'},// `params` 是与请求一起发送的 URL 参数// 必须是一个简单对象或 URLSearchParams 对象params: {ID: 12345},// `paramsSerializer`是可选方法,主要用于序列化`params`// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)paramsSerializer: function (params) {return Qs.stringify(params, {arrayFormat: 'brackets'})},// `data` 是作为请求体被发送的数据// 仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法// 在没有设置 `transformRequest` 时,则必须是以下类型之一:// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams// - 浏览器专属: FormData, File, Blob// - Node 专属: Stream, Bufferdata: {firstName: 'Fred'},// 发送请求体数据的可选语法// 请求方式 post// 只有 value 会被发送,key 则不会data: 'Country=Brasil&City=Belo Horizonte',// `timeout` 指定请求超时的毫秒数。// 如果请求时间超过 `timeout` 的值,则请求会被中断timeout: 1000, // 默认值是 `0` (永不超时)// `withCredentials` 表示跨域请求时是否需要使用凭证withCredentials: false, // default// `adapter` 允许自定义处理请求,这使测试更加容易。// 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。adapter: function (config) {/* ... */},// `auth` HTTP Basic Authauth: {username: 'janedoe',password: 's00pers3cret'},// `responseType` 表示浏览器将要响应的数据类型// 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'// 浏览器专属:'blob'responseType: 'json', // 默认值// `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)// 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求// Note: Ignored for `responseType` of 'stream' or client-side requestsresponseEncoding: 'utf8', // 默认值// `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称xsrfCookieName: 'XSRF-TOKEN', // 默认值// `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值// `onUploadProgress` 允许为上传处理进度事件// 浏览器专属onUploadProgress: function (progressEvent) {// 处理原生进度事件},// `onDownloadProgress` 允许为下载处理进度事件// 浏览器专属onDownloadProgress: function (progressEvent) {// 处理原生进度事件},// `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数maxContentLength: 2000,// `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数maxBodyLength: 2000,// `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。// 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),// 则promise 将会 resolved,否则是 rejected。validateStatus: function (status) {return status >= 200 && status < 300; // 默认值},// `maxRedirects` 定义了在node.js中要遵循的最大重定向数。// 如果设置为0,则不会进行重定向maxRedirects: 5, // 默认值// `socketPath` 定义了在node.js中使用的UNIX套接字。// e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。// 只能指定 `socketPath` 或 `proxy` 。// 若都指定,这使用 `socketPath` 。socketPath: null, // default// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http// and https requests, respectively, in node.js. This allows options to be added like// `keepAlive` that are not enabled by default.httpAgent: new http.Agent({ keepAlive: true }),httpsAgent: new https.Agent({ keepAlive: true }),// `proxy` 定义了代理服务器的主机名,端口和协议。// 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。// 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。// `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。// 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。// 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`proxy: {protocol: 'https',host: '127.0.0.1',port: 9000,auth: {username: 'mikeymike',password: 'rapunz3l'}},// 参见 https://axios-http.com/zh/docs/cancellationcancelToken: new CancelToken(function (cancel) {}),// `decompress` 表示响应体是否应该自动解压缩。// 如果设置为 `true`,还将从所有解压缩的响应对象中移除 'content-encoding' 头// 仅适用于 Node.js(XHR 无法关闭解压缩)decompress: true // 默认值
}
原文:Axios 请求配置,示例:post中嵌套了get请求
axios({url: '/api/XX/XX',method:'post',data: {username:'admin',password: '123456'}}).then((res) => {console.log(res.data.data.token)axios({url: '/api/XXX/XX',method: 'get',params: {id: 100},headers: {token: res.data.data.token //用户登录时生成的token}})}).catch((error) => {console.log(error)})
解决跨域问题
在 vue.config.js 文件中配置代理:
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({transpileDependencies: true,devServer: {port: 7070,proxy: {'/api': {target: 'http://localhost:8080',pathRewrite: {'^/api': '' //这里是将跨域时的/api替换为空字符串}}}}
})
Router
不同的访问路径,对应不同的页面展示,用不同视图组件替换vue单页面内容(vue 属于单页面应用)
npm install vue-router
路由组成
VueRouter:路由器,根据路由请求在路由视图中动态渲染对应的视图组件
<router-link>
:路由链接组件,浏览器会解析成超链接
<router-view>
:路由视图组件,用来展示与路由路径匹配的视图组件
路由配置
src/router/index.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'Vue.use(VueRouter)//维护路由表,某个路由路径对应哪个视图组件
const routes = [{path: '/',name: 'home',component: HomeView},{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/AboutView.vue')},{path: '/404',component: () => import('../views/404View.vue')},{//若请求的路由不存在,则跳转到/404页面path: '*',redirect: '/404'}
]const router = new VueRouter({routes
})export default router
App.vue
this.$router 是获取到路由对象
push方法是根据url进行跳转
使用编程武路由跳转两次跳转为同一个路径时会报错
再点击按钮时会报错,修改方法:
jump(){this.$router.push('/about',() => {})}
<template><div id="app"><nav><router-link to="/">Home</router-link> | <!--相当于超链接--><router-link to="/about">About</router-link> |<router-link to="/test">Test</router-link> |<input type="button" value="编程式路由跳转" @click="jump"/><!--相当于 <router-link to="/">Home</router-link>--></nav><!--视图组件展示的位置,相当于占位符,必须存在--><router-view/> //</div>
</template><script>
export default {methods: {jump() {//使用编程式路由跳转方式this.$router.push('/about')}}
}
</script><style>
#app {font-family: Avenir, Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;color: #2c3e50;
}nav {padding: 30px;
}nav a {font-weight: bold;color: #2c3e50;
}nav a.router-link-exact-active {color: #42b983;
}
</style>
嵌套路由实现步骤
概念:组件内要切换内容,就需要用到嵌套路由(子路由),可以理解为左侧为导航栏,点击任意一个部分可以仅更新指定区域的内容。
安装并导入 elementui,实现页面布局
若使用的时vue ui图形化界面创建的项目,则在创建项目时已经将对应的包导入了,无需执行下述指令:
npm i element-ui -S
更新main.js
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
//全局使用ElementUI
Vue.use(ElementUI);
完整main.js代码:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';Vue.config.productionTip = false//全局使用ElementUI
Vue.use(ElementUI);new Vue({router,render: h => h(App)
}).$mount('#app')
提供子视图组件,用于效果展示
在src/view/container创建P1View.vue、P2View.vue、P3View.vue三个.vue文件
下面展示其实一个子视图
<template><div>这是P1 View</div>
</template><script>
export default {}
</script><style>
.el-header, .el-footer {background-color: #B3C0D1;color: #333;text-align: center;line-height: 60px;}.el-aside {background-color: #D3DCE6;color: #333;text-align: center;line-height: 200px;}.el-main {background-color: #E9EEF3;color: #333;text-align: center;line-height: 160px;}body > .el-container {margin-bottom: 40px;}.el-container:nth-child(5) .el-aside,.el-container:nth-child(6) .el-aside {line-height: 260px;}.el-container:nth-child(7) .el-aside {line-height: 320px;}
</style>
在 src/router/index.js 中配置路由映射规则(嵌套路由配置)
src/router/index.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'Vue.use(VueRouter)//维护路由表,某个路由路径对应哪个视图组件
const routes = [{path: '/',name: 'home',component: HomeView},{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/AboutView.vue')},{path: '/404',component: () => import('../views/404View.vue')},{path: '/c',component: () => import('../views/container/ContainerView.vue'),redirect: '/c/p1',//嵌套路由(子路由),对应的组件会展示在当前组件内部children: [{path: '/c/p1',component: () => import('../views/container/P1View.vue')},{path: '/c/p2',component: () => import('../views/container/P2View.vue')},{path: '/c/p3',component: () => import('../views/container/P3View.vue')}]},{path: '*',redirect: '/404'}
]const router = new VueRouter({routes
})export default router
其中以下代码实现访问/c路由时默认跳转至/c/p1
{path: '/c',component: () => import('../views/container/ContainerView.vue'),redirect: '/c/p1',//嵌套路由(子路由),对应的组件会展示在当前组件内部children: [{path: '/c/p1',component: () => import('../views/container/P1View.vue')},{path: '/c/p2',component: () => import('../views/container/P2View.vue')},{path: '/c/p3',component: () => import('../views/container/P3View.vue')}]}
创建布局容器
src/views/container/ContainerView.vue文件
- 在布局容器视图中添加
<router-view>
,实现子视图组件展示 - 在布局容器视图中添加
<router-link>
,实现路由请求 - 子路由变化,切换的是【ContainerView 组件】中
<router-view></router-view>
部分的内容
<template><el-container><el-header>Header</el-header><el-container><el-aside width="200px"><router-link to="/c/p1">P1</router-link><br><router-link to="/c/p2">P2</router-link><br><router-link to="/c/p3">P3</router-link><br></el-aside><el-main><router-view/></el-main></el-container></el-container>
</template><script>
export default {}
</script><style>
.el-header, .el-footer {background-color: #B3C0D1;color: #333;text-align: center;line-height: 60px;}.el-aside {background-color: #D3DCE6;color: #333;text-align: center;line-height: 200px;}.el-main {background-color: #E9EEF3;color: #333;text-align: center;line-height: 160px;}body > .el-container {margin-bottom: 40px;}.el-container:nth-child(5) .el-aside,.el-container:nth-child(6) .el-aside {line-height: 260px;}.el-container:nth-child(7) .el-aside {line-height: 320px;}
</style>