Vue入门

vue简介

动态构建用户界面的渐进式JavaScript框架,作者尤雨溪。

vue的特点:

  • 遵循MVVM模式。
  • 编码简洁,体积小,运行效率高,适合移动/PC端开发。
  • 它本身只关注UI,可以引入其它第三方库开发项目。

Vue周边库:

  • vue-cli:vue脚手架
  • vue-resource
  • axios
  • vue-router:路由
  • vuex:状态管理
  • element-ui:基于vue的UI组件库

mvvm介绍

M: Model 数据模型

  • 数据可能是固定的思数据,更多的是来自服务器 ,从网络上请求下来的数据。

V: View 视图模板

  • 在前端开发中, 通常是DOM层,给用户展示各种信息。

VM: View-Model 视图模型

  • View和Model沟通的桥梁,双向数据绑定。

SPA(单页应用程序):单页Web应用(single page web application,SPA),就是只有一张Web页面的应用,是加载单个HTML 页面并在用户与应用程序交互时动态更新该页面的Web应用程序。

vue指令基本使用

CDN导入:

1
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

基本使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="app">
<div>我的:{{message}}</div>
<div v-text="message"></div>
<div v-text="array"></div>
<div v-text="dict"></div>
<div v-text="dict.name"></div>
<input type="button" v-on:click="doIt" value="单击"/>
<input type="button" @click="doIt" value="单击"/>
<input type="button" v-on:dblclick="doIt" value="双击"/><br>
<input type="text" v-model="message"/>
</div>
</body>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'hello vue!',
dict: {'name':'小明', 'age':18},
array: [1,2,3,4,5]
},
methods: {
doIt: function(){
alert(this.message=this.message+"hello");
}
},
created(){
//vue创建的时候调用
}
})
</script>
</html>

指令:

  • v-text:文本显示(与类似)
  • v-on:事件:绑定事件监听(可以用 @ 代替)
    • click:单击事件
    • dblclick:双击事件
    • keyup:键盘事件
    • 事件触发的函数可以传递参数
    • 事件的后面可以跟上.修饰符对事件进行限制(keyup.enter)
  • v-show:本质给元素设置display样式
  • v-if:本质操作dom,移除或添加元素
  • v-model:双向数据绑定
  • v-bind:属性:动态绑定属性(可以省略v-bind)
    • {}使用:v-bind:class=”{active:isActive}”
  • v-for:对数组进行遍历
    • 索引和内容:v-for=”(item, index) in arr”
  • v-once:后面不需要跟任何表达式,表示元素和组件只渲染一次, 不会随着数据的改变而变化。
  • v-pre:用于跳过这个元素和它子元素的编译过程, 用于显示原本的Mustache语法。

综合案例:实现笔记本功能

axios基本使用

Axios是一个开源的可以用在浏览器端和Node JS的异步通信框架, 她的主要作用就是实现AJAX异步通信。

axios特点:

  • 从浏览器中创建XMLHttpRequests

  • 从node.js创建http请求

  • 支持Promise API,JS中链式编程

  • 拦截请求和响应

  • 转换请求数据和响应数据

  • 取消请求

  • 自动转换JSON数据

  • 客户端支持防御XSRF(跨站请求伪造)

CDN导入:

1
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

原生基本使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<button class="get">get请求</button>
<button class="post">post请求</button>
</body>
<script>
document.querySelector(".get").onclick = function(){
axios.get("https://autumnfish.cn/api/joke/list?num=6")
.then(function(response){
console.log(response);
}),function(err){
alert(err);
}
}
document.querySelector(".post").onclick = function(){
axios.post("https://autumnfish.cn/api/user/reg",{username: "jack"})
.then(function(response){
console.log(response);
}),function(err){
alert(err);
}
}
document.querySelector(".get").onclick = function(){
axios.get("https://autumnfish.cn/api/joke/list?num=6")
.then(function(response){
console.log(response);
}),function(err){
alert(err);
}
}
</script>
</html>

axios结合vue基本使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<input type="button" value="获取笑话" @click="getJoke"/><br>
<span>{{joke}}</span>
</div>
</body>
<script>
var app = new Vue({
el: "#app",
data: {
joke: "笑话哦"
},
methods: {
getJoke: function(){
var that = this;
axios.get("https://autumnfish.cn/api/joke").then(
function(response){
that.joke = response.data;
},function(err){
console.log(err)
}
)
}
}
})
</script>
</html>

综合案例:音乐播放器

vue脚手架搭建

Vue CLI是官方发布的vue.js项目脚手架, 可以快速搭建vue开发环境以及webpack配置。

  • 统一的目录结构
  • 本地调试
  • 热部署
  • 单元测试
  • 集成打包上线

安装node.js:

淘宝镜像加速:(-g全局安装)

安装webpack:

  • cnpm install -g webpack webpack-cli

安装Vue Cli:

  • cnpm install -g @vue/cli
1
2
3
4
5
6
7
8
9
10
11
12
13
// 安装Vue脚手架 
npm install -g @vue/cli

// 上面安装的是Vue CLI3.0版本, 想要按照Vue CLI2的方式初始化项目时需要进行下列的命令
// 拉取2.x模板
// 'vue init' 的运行效果将会跟 'vue-cli@2.x' 相同
npm install -g @vue/cli-init

// Vue CLI2初始化项目 project -> 项目名称 英文
vue init webpack project

// Vue CLI3初始化项目 project -> 项目名称 英文
vue create project

创建Vue2项目:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 创建Vue CLI2项目
vue init webpack

? Project name vuecli2 --> 项目名字
? Project description test vue cli2 --> 项目描述
? Author lrw --> 作者
? Vue build --> 详解看下面一段
? Install vue-router? (Y/n) --> 安装路由
? Use ESlint to lint your code? (Y/n) --> ESlint审查代码是否符合编码规范和统一的代码风格
? Pick an ESLint preset --> 选择ESlint的规范 Standard
? Set up unit tests (Y/n) --> 单元测试
? Setup e2e tests with Nightwatch? (Y/n) --> 端对端测试
? Yes, use NPM
Yes, use Yarn

vue组件

组件(Component)是 Vue.js 最强大的功能之一,组件可以扩展 HTML 元素,封装可重用的代码。

使用组件步骤:

  • 在项目components文件夹下定义组件。
  • 在App.vue使用组件
    • 引入组件
    • 注册组件
    • 使用组件并给参数传值

MyComponent.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>
<div>
<!--使用参数-->
<h1>{{name}}</h1>
<div>{{age+1}}</div>
</div>
</template>

<script>
export default {
name: "MyComponent",
//组件中定义参数
props: {
//参数名: 参数类型
name: String,
age: Number
}
}
</script>

App.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
<div id="app">
<!--3、使用组件,给参数传值-->
<!--数值类型传参最好使用在参数前使用v-bind-->
<MyComponent name="小黑" :age="20"/>
</div>
</template>

<script>
//1、引入组件
import MyComponent from "@/components/MyComponent";

export default {
name: 'App',
//2、注册组件
components: {
MyComponent
}
}
</script>
<style>
</style>

vue路由

Vue Router是Vue.js官方的路由管理器。它和Vue.js的核心深度集成,让构建单页面应用变得易如反掌。

安装路由依赖:–save表示把添加的依赖写入到package.json

  • cnpm install –save vue-router

使用组件步骤:

  • 在终端当前项目下安装路由依赖。

  • 在src下新建views文件夹用于存放vue页面。

    • 新建Page.vue页面
  • 创建路由对象并定义路由规则

  • 在main.js文件中引入路由依赖并使用路由。

  • 在App.vue的template中通过显示路由页面

router/index.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import Vue from 'vue'
import Router from 'vue-router'
//引入路由页面
import Page from "../views/Page";

//使用路由
Vue.use(Router)

export default new Router({
//去除地址栏默认的 #
mode: 'history',
//定义路由规则
routes: [
{
path: '/page',
component: Page
},
]
})

main.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
//引入路由
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
el: '#app',
//使用路由
router,
components: { App },
template: '<App/>'
})

App.vue使用路由:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<template>
<div id="app">
<!--显示路由对应页面内容-->
<router-view/>
<br>
<hr>
<button @click="goFirst">显示first页面内容</button>
<br>
<button @click="goSecond">显示second页面内容</button>
</div>
</template>

<script>
export default {
name: 'App',
methods:{
goFirst(){
//通过push进行路由跳转
this.$router.push('/first');
},
goSecond(){
this.$router.push('/second');
}
}
}
</script>

<style>

</style>

Vue Element

Element,一套为开发者、设计师和产品经理准备的基于 Vue 的桌面端组件库。

element ui 官网:https://element.eleme.cn/#/zh-CN

安装element依赖:

  • vue2添加:cnpm install –save element-ui
  • vue3添加:cnpm install element-plus –save

vue2配置main.js:

1
2
3
4
5
6
7
8
9
10
11
12
import Vue from 'vue';
import App from './App.vue';
//引入element依赖
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
//使用element
Vue.use(ElementUI);

new Vue({
el: '#app',
render: h => h(App)
});

vue3配置main.js:

1
2
3
4
5
6
7
8
9
10
import { createApp } from 'vue'
import App from './App.vue'
//引入element依赖
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

const app = createApp(App)
//使用element
app.use(ElementPlus)
app.mount('#app')

Vue Axios

跨域问题的出现是因为浏览器的同源策略问题,所谓同源就是两个页面具有相同的协议(protocol),主机(host)和端口号(port),它是浏览器最核心也是最基本的功能,如果没有同源策略我们的浏览器将会十分的不安全,随时都可能受到攻击。当,协议名,域名,端口号,三者有一个不同都会发生跨域问题

使用axios进行接口请求会出现跨域问题,需在后端Controller层使用@CrossOrigin注解允许跨域请求。

如果使用axios发送post请求,请求参数在后端需要使用@RequestBody注解接收请求体参数。可以使用querystring组件,将请求参数转化为普通的表单数据,后端不需要使用@RequestBody注解。

安装axios依赖:

  • cnpm install –save axios

main.js配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import Vue from 'vue'
import App from './App'
import router from './router'
//引入axios依赖
import axios from 'axios'
//引入querystring
import querystring from 'querystring'

//设置全局属性,也就是在项目的任何地方都可以使用axios这个全局对象 prototype ==> 原型对象
Vue.prototype.$axios = axios

//设置全局使用querystring
Vue.prototype.$querystring = querystring

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})

通过this.$调用全局属性:

1
this.$axios.post(url, this.$querystring.stringify({键: 请求参数}))

请求代理

在前端项目中,可以使用请求代理方式解决浏览器跨域问题。前端项目接收axios发送的请求,代理axios请求后端服务器,绕过浏览器同源策略。

项目根目录新建:vue.config.js

  • 配置代理

vue.config.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
module.exports = {
devServer: {
//设置前端项目的端口号
port:8080,
proxy: {
//可以配置多个代理信息 每一个代理使用key:value形式
//代理的名字代表请求路径 login代表前端访问他访问地址为http://localhost:8080/xxx
'/api': {
//出发代理后把请求转发到哪
//转发后的地址为http://localhost:8081/xxx
target : 'http://localhost:8081/',
//请求路径是否重写
ws: true,
pathRewrite : {
//去除原始请求路径中的/api /api/login ==> http://localhost:8081/login
'^/api' : ''
},
//解决跨域问题,后端不需要再写@CrossOrigin注解
changeOrigin: true
}
}
}
}

注意:修改完该配置文件,需重启前端项目才可以生效。

创建vue项目使用命令vue init webpack 项目名称的方式,vue.config.js配置不生效,生效的是webpack.dev.conf.js。需要在config/index.js文件中的proxyTable配置请求代理。