最近好焦虑 我想去开个婚纱摄影店 也想开个服装店 但是上了这么多年学我还是有点不甘心的 唉 我只希望每天的天气好一点 困难少一点 敏感少一点
祝大家每天开心 事事顺心 坚定地走完自己选择的路 如果太累了 那就多睡睡觉 多吃点好吃的 慢下来看看世界的美好
npm install -g @vue/cli
vue ui
进入项目目录,执行
npm run serve
前端服务器默认占用了 8080 端口,需要修改一下
文档地址:DevServer | webpack
打开 vue.config.js 添加
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
// ...
devServer: {
port: 7070
}
})
为了避免前后端服务器联调时, fetch、xhr 请求产生跨域问题,需要配置代理
文档地址同上
打开 vue.config.js 添加
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
// ...
devServer: {
port: 7070,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
}
}
}
})
PS D:\2022.js\代码\第3章\client> tree src
D:\2022.JS\代码\第3章\CLIENT\SRC
├─assets
├─components
├─router
├─store
└─views
以后还会添加
Vue 的组件文件以 .vue 结尾,每个组件由三部分组成
<template>template>
<script>script>
<style>style>
入口组件是 App.vue
先删除原有代码,来个 Hello, World 例子
<template>
<h1>{{msg}}h1>
template>
<script>
export default {
data() {
return {
msg: "Hello, Vue!"
}
}
}
script>
解释
{{}}
在 Vue 里称之为插值表达式,用来绑定 data 方法返回的对象属性,绑定的含义是数据发生变化时,页面显示会同步变化<template>
<div>
<h1>{{ name }}h1>
<h1>{{ age > 60 ? '老年' : '青年' }}h1>
div>
template>
<script>
const options = {
data: function () {
return { name: '张三', age: 70 };
}
};
export default options;
script>
{{}}
里只能绑定一个属性,绑定多个属性需要用多个 {{}}
分别绑定<template>
<div>
<div><input type="text" v-bind:value="name">div>
<div><input type="date" v-bind:value="birthday">div>
<div><input type="text" :value="age">div>
div>
template>
<script>
const options = {
data: function () {
return { name: '王五', birthday: '1995-05-01', age: 20 };
}
};
export default options;
script>
<template>
<div>
<div><input type="button" value="点我执行m1" v-on:click="m1">div>
<div><input type="button" value="点我执行m2" @click="m2">div>
<div>{{count}}div>
div>
template>
<script>
const options = {
data: function () {
return { count: 0 };
},
methods: {
m1() {
this.count ++;
console.log("m1")
},
m2() {
this.count --;
console.log("m2")
}
}
};
export default options;
script>
<template>
<div>
<div>
<label for="">请输入姓名label>
<input type="text" v-model="name">
div>
<div>
<label for="">请输入年龄label>
<input type="text" v-model="age">
div>
<div>
<label for="">请选择性别label>
男 <input type="radio" value="男" v-model="sex">
女 <input type="radio" value="女" v-model="sex">
div>
<div>
<label for="">请选择爱好label>
游泳 <input type="checkbox" value="游泳" v-model="fav">
打球 <input type="checkbox" value="打球" v-model="fav">
健身 <input type="checkbox" value="健身" v-model="fav">
div>
div>
template>
<script>
const options = {
data: function () {
return { name: '', age: null, sex:'男' , fav:['打球']};
},
methods: {
}
};
export default options;
script>
<!-- 计算属性 -->
<template>
<div>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
</div>
</template>
<script>
const options = {
data: function () {
return { firstName: '三', lastName: '张' };
},
/* methods: {
fullName() {
console.log('进入了 fullName')
return this.lastName + this.firstName;
}
},*/
computed: {
fullName() {
console.log('进入了 fullName')
return this.lastName + this.firstName;
}
}
};
export default options;
axios 它的底层是用了 XMLHttpRequest(xhr)方式发送请求和接收响应,xhr 相对于之前讲过的 fetch api 来说,功能更强大,但由于是比较老的 api,不支持 Promise,axios 对 xhr 进行了封装,使之支持 Promise,并提供了对请求、响应的统一拦截功能
安装
npm install axios -S
导入
import axios from 'axios'
方法
请求 | 备注 |
---|---|
axios.get(url[, config]) | ⭐️ |
axios.delete(url[, config]) | |
axios.head(url[, config]) | |
axios.options(url[, config]) | |
axios.post(url[, data[, config]]) | ⭐️ |
axios.put(url[, data[, config]]) | |
axios.patch(url[, data[, config]]) |
例子
<template>
<div>
<input type="button" value="获取远程数据" @click="sendReq()">
</div>
</template>
<script>
import axios from 'axios'
const options = {
methods: {
async sendReq() {
// 1. 演示 get, post
// const resp = await axios.post('/api/a2');
// 2. 发送请求头
// const resp = await axios.post('/api/a3',{},{
// headers:{
// Authorization:'abc'
// }
// });
// 3. 发送请求时携带查询参数 ?name=xxx&age=xxx
// const name = encodeURIComponent('&&&');
// const age = 18;
// const resp = await axios.post(`/api/a4?name=${name}&age=${age}`);
// 不想自己拼串、处理特殊字符、就用下面的办法
// const resp = await axios.post('/api/a4', {}, {
// params: {
// name:'&&&&',
// age: 20
// }
// });
// 4. 用请求体发数据,格式为 urlencoded
// const params = new URLSearchParams();
// params.append("name", "张三");
// params.append("age", 24)
// const resp = await axios.post('/api/a4', params);
// 5. 用请求体发数据,格式为 multipart
// const params = new FormData();
// params.append("name", "李四");
// params.append("age", 30);
// const resp = await axios.post('/api/a5', params);
// 6. 用请求体发数据,格式为 json
const resp = await axios.post('/api/a5json', {
name: '王五',
age: 50
});
console.log(resp);
}
}
};
export default options;
</script>
创建实例
const _axios = axios.create(config);
常见的 config 项有
名称 | 含义 |
---|---|
baseURL | 将自动加在 url 前面 |
headers | 请求头,类型为简单对象 |
params | 跟在 URL 后的请求参数,类型为简单对象或 URLSearchParams |
data | 请求体,类型有简单对象、FormData、URLSearchParams、File 等 |
withCredentials | 跨域时是否携带 Cookie 等凭证,默认为 false |
responseType | 响应类型,默认为 json |
例
const _axios = axios.create({
baseURL: 'http://localhost:8080',
withCredentials: true
});
await _axios.post('/api/a6set')
await _axios.post('/api/a6get')
响应格式
名称 | 含义 |
---|---|
data | 响应体数据 ⭐️ |
status | 状态码 ⭐️ |
headers | 响应头 |
请求拦截器
_axios.interceptors.request.use(
function(config) {
// 比如在这里添加统一的 headers
return config;
},
function(error) {
return Promise.reject(error);
}
);
响应拦截器
_axios.interceptors.response.use(
function(response) {
// 2xx 范围内走这里
return response;
},
function(error) {
// 超出 2xx, 比如 4xx, 5xx 走这里
return Promise.reject(error);
}
);
<template>
<div>
<input type="button" value="获取远程数据" @click="sendReq()">
<div class="title">学生列表</div>
<div class="thead">
<div class="row bold">
<div class="col">编号</div>
<div class="col">姓名</div>
<div class="col">性别</div>
<div class="col">年龄</div>
</div>
</div>
<div class="tbody">
<div class="row" v-if="students.length > 0">显示学生数据</div>
<div class="row" v-else>暂无学生数据</div>
</div>
</div>
</template>
<script>
import axios from '../util/myaxios'
const options = {
data: function() {
return {
students: []
};
},
methods : {
async sendReq() {
const resp = await axios.get("/api/students");
console.log(resp.data.data)
this.students = resp.data.data;
}
}
};
export default options;
</script>
<style scoped>
div {
font-family: 华文行楷;
font-size: 20px;
}
.title {
margin-bottom: 10px;
font-size: 30px;
color: #333;
text-align: center;
}
.row {
background-color: #fff;
display: flex;
justify-content: center;
}
.col {
border: 1px solid #f0f0f0;
width: 15%;
height: 35px;
text-align: center;
line-height: 35px;
}
.bold .col {
background-color: #f1f1f1;
}
</style>
<template>
<div>
<!-- <input type="button" value="获取远程数据" @click="sendReq()"> -->
<div class="title">学生列表</div>
<div class="thead">
<div class="row bold">
<div class="col">编号</div>
<div class="col">姓名</div>
<div class="col">性别</div>
<div class="col">年龄</div>
</div>
</div>
<div class="tbody">
<div v-if="students.length > 0">
<div class="row" v-for="s of students" :key="s.id">
<div class="col">{{s.id}}</div>
<div class="col">{{s.name}}</div>
<div class="col">{{s.sex}}</div>
<div class="col">{{s.age}}</div>
</div>
</div>
<div class="row" v-else>暂无学生数据</div>
</div>
</div>
</template>
<script>
import axios from '../util/myaxios'
const options = {
mounted: function(){
this.sendReq()
},
data: function() {
return {
students: []
};
},
methods : {
async sendReq() {
const resp = await axios.get("/api/students");
console.log(resp.data.data)
this.students = resp.data.data;
}
}
};
export default options;
</script>
<style scoped>
div {
font-family: 华文行楷;
font-size: 20px;
}
.title {
margin-bottom: 10px;
font-size: 30px;
color: #333;
text-align: center;
}
.row {
background-color: #fff;
display: flex;
justify-content: center;
}
.col {
border: 1px solid #f0f0f0;
width: 15%;
height: 35px;
text-align: center;
line-height: 35px;
}
.bold .col {
background-color: #f1f1f1;
}
</style>
按钮组件
<template>
<div class="button" :class="[type,size]">
a<slot></slot>b
</div>
</template>
<script>
const options = {
props: ["type", "size"]
};
export default options;
</script>
使用组件
<template>
<div>
<h1>父组件</h1>
<my-button type="primary" size="small">1</my-button>
<my-button type="danger" size="middle">2</my-button>
<my-button type="success" size="large">3</my-button>
</div>
</template>
<script>
import MyButton from '../components/MyButton.vue'
const options = {
components: {
MyButton
}
};
export default options;
</script>
安装
npm install element-ui -S
引入组件
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(Element)
测试,在自己的组件中使用 ElementUI 的组件
按钮
搜索
''
表示用户没有选择的情况0,20
会被 spring 转换为 new int[]{0, 20}
''
会被 spring 转换为 new int[0]
级联选择器中选项的数据结构为
[
{value:100, label:'主页',children:[
{value:101, label:'菜单1', children:[
{value:105, label:'子项1'},
{value:106, label:'子项2'}
]},
{value:102, label:'菜单2', children:[
{value:107, label:'子项3'},
{value:108, label:'子项4'},
{value:109, label:'子项5'}
]},
{value:103, label:'菜单3', children:[
{value:110, label:'子项6'},
{value:111, label:'子项7'}
]},
{value:104, label:'菜单4'}
]}
]
下面的例子是将后端返回的一维数组【树化】
vue 属于单页面应用,所谓的路由,就是根据浏览器路径不同,用不同的视图组件替换这个页面内容展示
新建一个路由 js 文件,例如 src/router/example14.js,内容如下
import Vue from 'vue'
import VueRouter from 'vue-router'
import ContainerView from '@/views/example14/ContainerView.vue'
import LoginView from '@/views/example14/LoginView.vue'
import NotFoundView from '@/views/example14/NotFoundView.vue'
Vue.use(VueRouter)
const routes = [
{
path:'/',
component: ContainerView
},
{
path:'/login',
component: LoginView
},
{
path:'/404',
component: NotFoundView
}
]
const router = new VueRouter({
routes
})
export default router
在 main.js 中采用我们的路由 js
import Vue from 'vue'
import e14 from './views/Example14View.vue'
import router from './router/example14' // 修改这里
import store from './store'
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.config.productionTip = false
Vue.use(Element)
new Vue({
router,
store,
render: h => h(e14)
}).$mount('#app')
根组件是 Example14View.vue,内容为:
起到占位作用,改变路径后,这个路径对应的视图组件就会占据
的位置,替换掉它之前的内容import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path:'/',
component: () => import('@/views/example14/ContainerView.vue')
},
{
path:'/login',
component: () => import('@/views/example14/LoginView.vue')
},
{
path:'/404',
component: () => import('@/views/example14/NotFoundView.vue')
}
]
const router = new VueRouter({
routes
})
export default router
组件内再要切换内容,就需要用到嵌套路由(子路由),下面的例子是在【ContainerView 组件】内定义了 3 个子路由
const routes = [
{
path:'/',
component: () => import('@/views/example14/ContainerView.vue'),
redirect: '/c/p1',
children: [
{
path:'c/p1',
component: () => import('@/views/example14/container/P1View.vue')
},
{
path:'c/p2',
component: () => import('@/views/example14/container/P2View.vue')
},
{
path:'c/p3',
component: () => import('@/views/example14/container/P3View.vue')
}
]
},
{
path:'/login',
component: () => import('@/views/example14/LoginView.vue')
},
{
path:'/404',
component: () => import('@/views/example14/NotFoundView.vue')
},
{
path:'*',
redirect: '/404'
}
]
子路由变化,切换的是【ContainerView 组件】中
部分的内容
<template>
<div class="container">
<router-view></router-view>
</div>
</template>
通常主页要做布局,下面的代码是 ElementUI 提供的【上-【左-右】】布局
P1
P2
P3
jump 方法
菜单1
子项1
子项2
子项3
菜单2
菜单3
包裹起来el-menu
标签上加上 router
属性,表示结合导航菜单与路由对象,此时,就可以利用菜单项的 index
属性来路由跳转将菜单、路由信息(仅主页的)存入数据库中
insert into menu(id, name, pid, path, component, icon) values
(101, '菜单1', 0, '/m1', null, 'el-icon-platform-eleme'),
(102, '菜单2', 0, '/m2', null, 'el-icon-delete-solid'),
(103, '菜单3', 0, '/m3', null, 'el-icon-s-tools'),
(104, '菜单4', 0, '/m4', 'M4View.vue', 'el-icon-user-solid'),
(105, '子项1', 101, '/m1/c1', 'C1View.vue', 'el-icon-s-goods'),
(106, '子项2', 101, '/m1/c2', 'C2View.vue', 'el-icon-menu'),
(107, '子项3', 102, '/m2/c3', 'C3View.vue', 'el-icon-s-marketing'),
(108, '子项4', 102, '/m2/c4', 'C4View.vue', 'el-icon-s-platform'),
(109, '子项5', 102, '/m2/c5', 'C5View.vue', 'el-icon-picture'),
(110, '子项6', 103, '/m3/c6', 'C6View.vue', 'el-icon-upload'),
(111, '子项7', 103, '/m3/c7', 'C7View.vue', 'el-icon-s-promotion');
不同的用户查询的的菜单、路由信息是不一样的
例如:访问 /api/menu/admin
返回所有的数据
[
{
"id": 102,
"name": "菜单2",
"icon": "el-icon-delete-solid",
"path": "/m2",
"pid": 0,
"component": null
},
{
"id": 107,
"name": "子项3",
"icon": "el-icon-s-marketing",
"path": "/m2/c3",
"pid": 102,
"component": "C3View.vue"
},
{
"id": 108,
"name": "子项4",
"icon": "el-icon-s-platform",
"path": "/m2/c4",
"pid": 102,
"component": "C4View.vue"
},
{
"id": 109,
"name": "子项5",
"icon": "el-icon-picture",
"path": "/m2/c5",
"pid": 102,
"component": "C5View.vue"
}
]
访问 /api/menu/wang
返回
[
{
"id": 103,
"name": "菜单3",
"icon": "el-icon-s-tools",
"path": "/m3",
"pid": 0,
"component": null
},
{
"id": 110,
"name": "子项6",
"icon": "el-icon-upload",
"path": "/m3/c6",
"pid": 103,
"component": "C6View.vue"
},
{
"id": 111,
"name": "子项7",
"icon": "el-icon-s-promotion",
"path": "/m3/c7",
"pid": 103,
"component": "C7View.vue"
}
]
前端根据他们身份不同,动态添加路由和显示菜单
export function addServerRoutes(array) {
for (const { id, path, component } of array) {
if (component !== null) {
// 动态添加路由
// 参数1:父路由名称
// 参数2:路由信息对象
router.addRoute('c', {
path: path,
name: id,
component: () => import(`@/views/example15/container/${component}`)
});
}
}
}
在用户注销时应当重置路由
export function resetRouter() {
router.matcher = new VueRouter({ routes }).matcher
}
页面刷新后,会导致动态添加的路由失效,解决方法是将路由数据存入 sessionStorage
页面刷新,重新创建路由对象时,从 sessionStorage 里恢复路由数据
const router = new VueRouter({
routes
})
// 从 sessionStorage 中恢复路由数据
const serverRoutes = sessionStorage.getItem('serverRoutes');
if(serverRoutes) {
const array = JSON.parse(serverRoutes);
addServerRoutes(array) // 动态添加路由
}
代码部分
菜单部分
{{m1.name}}
{{m2.name}}
{{m1.name}}
vuex 可以在多个组件之间共享数据,并且共享的数据是【响应式】的,即数据的变更能及时渲染到模板
首先需要定义 state 与 mutations 他们一个用来读取共享数据,一个用来修改共享数据
src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
/*
读取数据,走 state, getters
修改数据,走 mutations, actions
*/
export default new Vuex.Store({
state: {
name: '',
age: 18
},
getters: {
},
mutations: {
updateName(state, name) {
state.name = name;
}
},
actions: {
},
modules: {
}
})
修改共享数据
修改
store.commit(mutation方法名, 参数)
来间接调用读取共享数据
欢迎您:{{ $store.state.name }}, {{ $store.state.age }}
每次去写 $store.state.name
这样的代码显得非常繁琐,可以用 vuex 帮我们生成计算属性
欢迎您:{{ name }}, {{ age }}
...
展开运算符,填充入 computed 即可使用
修改
mutations 方法内不能包括修改不能立刻生效的代码,否则会造成 Vuex 调试工具工作不准确,必须把这些代码写在 actions 方法中
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
/*
读取数据,走 state, getters
修改数据,走 mutations, actions
*/
import axios from '@/util/myaxios'
export default new Vuex.Store({
state: {
name: '',
age: 18
},
getters: {
},
mutations: {
updateName(state, name) {
state.name = name;
},
// 错误的用法,如果在mutations方法中包含了异步操作,会造成开发工具不准确
/* async updateServerName(state) {
const resp = await axios.get('/api/user');
const {name, age} = resp.data.data;
state.name = name;
state.age = age;
} */
updateServerName(state, user) {
const { name, age } = user;
state.name = name;
state.age = age;
}
},
actions: {
async updateServerName(context) {
const resp = await axios.get('/api/user');
context.commit('updateServerName', resp.data.data)
}
},
modules: {
}
})
页面使用 actions 的方法可以这么写
从服务器获取数据,存入store
mapActions 会生成调用 actions 中方法的代码
调用 actions 的代码内部等价于,它返回的是 Promise 对象,可以用同步或异步方式接收结果
this.$store.dispatch('action名称', 参数)