文章目录
一.Vue.js 介绍
1.什么是Vue.js
Vue.js 是一个构建数据驱动的web界面的渐进式框架。Vue.js 的目标通过尽可能简单的API实现相应的数据绑定和组合的视图组件。核心是一个响应式的数据绑定系统。
2.Vue的特点
3.Vue的优势
Vue是轻量级框架、简单易学、双向数据绑定,组件化,视图,数据和结构的分离,虚拟DOM,运行速度快。
而且 Vue 是一个单页面应用,使页面局部刷新,不用每次跳转页面都请求所有的数据和dom,这样大大加快了访问速度和提升用户体验,而且他们第三方ui库很多节省开发时间
4.Vue的响应式原理(MVVM)
Vue有一个重要的特点是当数据发生改变时,可以自动更新视图,那这个事怎么实现的,这是因为Vue采用了MVVM的架构模式。
Vue ------监听------>View Model --------改变------> Model
------更新-----------|----------------监听读取-----|
可以看到MVVM是个MVC的增强版,正式连接了视图和模型,将表示逻辑Controller 移出放到一个新的对象里,即ViewModel,他实现了View和Model的自动同步,即当Model属性改变时,我们不用自己手动操作Dom元素来改变View的显示,而是改变属性后该属性对应的view层数据会自动改变
二.Vue 基础语法
首先下载vue框架
1.数据绑定
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
用户名:{{name}} <br>
qq:{{qq}}
</div>
<script src="./js/vue.js"></script>
<script>
var app = new Vue({
el:"#app",
data:{
name:"张三",
qq:"33333"
}
})
</script>
</body>
</html>
2.钩子函数
var app = new Vue({
el:"#app",
data:{
name:"张三",
qq:"33333",
},
methods:{
fun1:function () {
alert(this.name);
}
},
mounted:function () { // 钩子函数, 加载后
console.log("destroyed");
this.fun1();
}
})
3.属性绑定
v-bind
<body>
<div id="app">
name: <input type="text" v-bind:value="name"> <br>
<a v-bind:href="myurl"> 百度 </a>
<br>
<!-- 简化 -->
name: <input type="text" :value="name"> <br>
<a :href="myurl"> 百度 </a>
</div>
<script src="./js/vue.js"></script>
<script>
var app = new Vue({
el:"#app",
data:{
name:"张三",
myurl:"http://www.baidu.com"
},
})
</script>
</body>
4.内嵌html或文本
v-text
v-html
v-show = “true” 是否显示
<body>
<div id="app">
<!-- 用户名:{{name}} <br>-->
用户名: <span v-text="name"></span> <br>
密码: <span v-html="html"></span>
</div>
<script src="./js/vue.js"></script>
<script>
var app = new Vue({
el:"#app",
data:{
name:"张三",
html:"<input type=\"text\">"
},
})
</script>
</body>
5.if语句
v-if
v-else-if
v-else
<body>
<div id="app">
<div v-if="amount > 100">库存充足</div>
<div v-else-if="amount > 10">库存不足</div>
<div v-else>库存稀缺</div>
</div>
<script src="./js/vue.js"></script>
<script>
var app = new Vue({
el:"#app",
data:{
amount:10,
}
})
</script>
</body>
6.for循环
v-for
<body>
<div id="app">
<ul>
<li v-for="(item,index) in list">{{index}}--->{{item.name}}</li>
</ul>
</div>
<script src="./js/vue.js"></script>
<script>
var app = new Vue({
el:"#app",
data:{
list:[
{name:"zhangsan"},
{name:"lisi"},
{name:"wangwu"},
]
}
})
</script>
</body>
7,双向绑定
Vue.js 是一个MVVM框架,即数据双向绑定,即当数据发生变化的时候,视图也就发生变化,当视图发生变化的时候,数据也会跟着同步变化。这也算是Vue.js的精髓之处了。
值得注意的是,我们所说的数据双向绑定,一定是对于 UI 控件来说的,非 UI 控件不会涉及到数据双向绑定。单向数据绑定是使用状态管理工具的前提。
如何实现双向绑定数据
v-model
v-model 指令可以在表单及元素上创建双向数据绑定,它会根据空间类型自动选取正确的方法来更新元素。他负责监听用户的输入事件以更新数据,并对一些极端场景进行一些特殊处理
注意:v-model 会忽略所有表单元素 value,checked,selected 特性的初始值 而总是将vue实例的数据作为数据来源。你应该通过JavaScript在组件的data选项中声明初始值!
input标签
<body>
<div id="app">
<input type="text" v-model="msg">
<div>{{msg}}</div>
</div>
<script src="./js/vue.js"></script>
<script>
var app = new Vue({
el:"#app",
data:{
msg:"hello"
}
})
</script>
</body>
下拉列表框
<body>
<div id="app">
<select v-model="msg">
<option selected value="请选择">请选择</option>
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="广州">广州</option>
<option value="深圳">深圳</option>
</select>
<div>{{msg}}</div>
</div>
<script src="./js/vue.js"></script>
<script>
var app = new Vue({
el:"#app",
data:{
msg:"请选择"
}
})
</script>
</body>
8.事件绑定
v-on
v-on:事件名 = “方法名”
简写: @事件名 = “方法名”
事件名有哪些: click|keydown|keyup|mouseover|mouseout|自定义事件名
<body>
<div id="app">
<input type="button" value="-" v-on:click="sub">
<input type="text" v-model="num">
<input type="button" value="+" v-on:click="plus">
</div>
<script src="./js/vue.js"></script>
<script>
var app = new Vue({
el:"#app",
data:{
num:0
},
methods:{
sub:function () {
if(this.num > 0){
this.num -= 1
}
},
plus:function () {
this.num = parseInt(this.num) + 1
}
}
})
</script>
</body>
9.Template 标签
-
作用一:作为模版占位符,可以帮助我们包裹元素,template不会被渲染到页面上
<body> <div id="app"> <template v-for="item in list"> <a href="#">{{item}}</a> </template> </div> <script src="./js/vue.js"></script> <script> var app = new Vue({ el:"#app", data:{ list:[1,2,3,4,5] } }) </script> </body>
-
作用二:作为 HTML 模版
原生写法: 将 el 元素 替换为 template,template 里面必须有且只有一个跟标签
<body> <div id="app"> hello world </div> <script src="./js/vue.js"></script> <script> var app = new Vue({ el:"#app", template:"<div>HHeellooww</div>" }) </script> </body>
标签写法:将 #app 标签替换为 #1 ,且template 里面有且只有一个跟标签
<body> <div id="app"> hello world </div> <template id="t1"> <div> HHEELLOOWW </div> </template> <script src="./js/vue.js"></script> <script> var app = new Vue({ el:"#app", template:"#t1" }) </script> </body>
10.组件
组件(Component)是vue.js 最强大的功能之一
组件可以扩展html元素,封装可重用代码
组件系统让我们可以用独立可重用的小组件来构建大型应用,机会任意的应用的界面都可以抽象为一个组件树
<body>
<div id="app">
hello world
<c1></c1>
</div>
<script src="./js/vue.js"></script>
<script>
Vue.component("c1",{
data:function () {
return{
msg:"hello"
}
},
template:"<div>{{msg}}</div>"
})
var app = new Vue({
el:"#app"
});
</script>
</body>
可以单独把 template 抽离出来
- 全局组件:
自定义组件:
自定义一个组件hello.vue
<template>
<div> {{msg}} </div>
</template>
<script>
module.exports = {
data:function() {
return{
msg:"hello world 111 222 33"
}
}
}
</script>
使用:注意导入httpVueLoader.js工具
<body>
<div id="app">
<hello></hello>
</div>
<script src="./js/vue.js"></script>
<script src="./js/httpVueLoader.js"></script>
<script>
var app = new Vue({
el:"#app",
components:{
"hello":httpVueLoader("./hello.vue")
}
});
</script>
</body>
- 局部组件
<body>
<div id="app">
<hello></hello>
</div>
<script src="./js/vue.js"></script>
<script src="./js/httpVueLoader.js"></script>
<script>
var a = {
data:function () {
return{
msg:"hello 啊",
}
},
template:"<div>{{msg}}</div>"
}
var app = new Vue({
el:"#app",
components:{
"hello":a
}
});
</script>
</body>
- 父子组件
<body>
<div id="app">
<f></f>
</div>
<script src="./js/vue.js"></script>
<script>
var f = {
template:"<div>父组件<son></son></div>",
components:{
son:{
template: "<div>zi组件</div>"
}
}
}
new Vue({
el:"#app",
components: {
f:f
}
})
</script>
</body>
11.动态传值
格式:props:[‘value’] data 里面的数据传递到组件里面的props属性
<body>
<div id="app">
<c v-html="msg"></c>
</div>
<script src="./js/vue.js"></script>
<script>
Vue.component("c",{
props:["value"],
template:"<div>{{value}}</div>"
})
new Vue({
el:"#app",
data:{
msg:"hello"
}
})
</script>
</body>
传递一个数组
<body>
<div id="app">
<c v-for="item in msg" v-html="item"></c>
</div>
<script src="./js/vue.js"></script>
<script>
Vue.component("c",{
props:["value"],
template:"<div>{{value}}</div>"
})
new Vue({
el:"#app",
data:{
msg:['h','e','l','l','o','w']
}
})
</script>
</body>
12.Watch监视
vue‘的选项很多,除了前面用到的el,data,methods等,该有其他的,比如watch
数据变化的监控经常使用比如天气预报的穿衣指数,它主要是根据温度来进行提示的。温度大于25度,我们建议穿T恤,温度小于25大于0,我们建议穿毛衣外套,温度小于0度是我们建议穿棉衣羽绒服
<body>
<div id="app">
<div>温度:{{temperature}}</div>
<div>建议:{{advise}}</div>
<input type="text" v-model="temperature">
</div>
<script src="./js/vue.js"></script>
<script>
new Vue({
el:"#app",
data:{
temperature:"",
advise:""
},
watch:{
temperature: function (newVal,oldVal) { // 固定格式 ,newVal表示 新的值 ,oldVal表示旧的值
if(newVal>25){
this.advise="建议穿T恤";
}else if(newVal>0){
this.advise="建议穿外套";
}else{
this.advise="建议穿棉衣";
}
}
}
})
</script>
</body>
三.Axios异步通信
1.什么是Axios?
Axios 是一个类库,基于Promise管理的Http库,是前端通信框架,可以用来在浏览器和 node.js 中,axios实现了对ajax的封装,常用于Ajax请求
注意: promise 是 java script 的一个对象,代表了未来将要发生的事件,用来传递异步操作的消息
2.Axios和Ajax的关系
Axios 是Ajax技术的一种实现,就像Jquery中$.ajax 也是Ajax的一种实现
Axios是通过Promise实现XHR封装,其中Promise是控制手段,XHR是实际发送HTTP请求的客户端。
Jquery中的$.ajax 是通过callback + XHR 实现(XHR 就是 XmlHttpRequest对象)
在通俗一点讲: Ajax 是汽车,Axios 是奥迪,$.ajax是奔驰
3.Axios的API
使用首先需要导入:
axios({
method:‘get’,
url:‘url’,
data:{
id:1,
name:‘aa’
}
})
axios.get('url',{'参数'}).then(resp=>(this.user=>resp.data))
axios.post('url',{'参数'}).then(resp=>(this.user=>resp.data))
axios.put('url',{'参数'}).then(resp=>(this.user=>resp.data))
axios.delete('url',{'参数'}).then(resp=>(this.user=>resp.data))
这里的参数是 json 格式
demo1
<body>
<div id="app">
<input type="text" v-model="student.sid">
<input type="button" value="获取" @click="getStudent(student.sid)">
<div>sid:{{student.sid}}</div>
<div>name:{{student.name}}</div>
<div>age:{{student.age}}</div>
</div>
<script src="./js/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: "#app",
data: {
student:{
sid: "",
name: "",
age: ""
}
},
methods: {
getStudent: function (sid) { // 这里使用箭头函数 不用声明this指向
axios.get("http://localhost:8080/student/"+sid).then(res => {
this.student=res.data
})
}
}
})
</script>
</body>
四.前端工程化vue-cli
Vue是渐进式框架,您可以用它一个功能,也可以用全家桶,前面的章节中,我们是在html中引入的vue.js,只用他的核心数据绑定功能。但基于vue的扩展还有很多,比如vueRouter,axios,elementUI等
vue-cli ,它是一个专门的为单页面应用快速搭建繁杂的Vue脚手架,通俗的说就是代码生成器,可以快速生成一套基于Vue完整的前端框架,单独编译,单独部署。可以集成各种第三方插件,扩展出更多的功能。
也就是:Vue cli = Vue + 一堆js插件
利用Vue-cli脚手架来构建Vue项目需要首先安装Node.js 和 NPM 环境
之后利用 npm 安装 vue-cli: npm install -g vue-cli
1.创建第一个脚手架项目
命令:vue create vue项目名
启动服务:进入项目目录;npm run serve
或者 vue ui
2.展示一个vue 组件
-
在 views 中 创建一个 News.vue
<template> 这是新闻列表 </template>
-
在 router > index.js 中 进行注册
import { createRouter, createWebHashHistory } from "vue-router"; // 这里采用延迟加载的方式 const routes = [ { path: "/", name: "News", // 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("../views/News.vue"), } ]; const router = createRouter({ history: createWebHashHistory(), routes, }); export default router;
-
然后放在 App.vue 中进行使用
<template> <div> <!-- 默认为跟路径 --> <router-view /> </div> </template>
3.页面间跳转
<router-link :to="{path:'/NewDetail',query:{id:1}}">新闻1</router-link>
接收
<template>
<div id="NewDetail">
这是新闻详情页 <span></span>
</div>
</template>
<script>
export default {
el:"#NewDetail",
data:function(){
return{
id:""
}
},
mounted:function(){
var id = this.$route.query.id;
this.id = id;
console.log(id);
}
}
</script>
4.函数跳转
this.$router.push("/")
5.在Vue中使用axios
首先安装 : npm install axios
然后在 main.js 中配置
// 导入 axios
import axios from "axios";
var app =createApp(App);
// 配置全句访问
app.config.globalProperties.$axios = axios
app.use(store).use(router).mount("#app");
6.解析字符串 qs
安装 与 配置 : 与 axios 类似
案例:基于springboot的 增删改查 操作
App.vue
<template>
<div >
<router-view />
</div>
</template>
Students.vue
<template>
<h2>学生列表页</h2>
<router-link :to="{path:'/AddStudent'}">添加</router-link>
<table width="500" border="1" align="center">
<tr>
<th>学生id</th>
<th>学生姓名</th>
<th>学生年龄</th>
<th>删除</th>
<th>修改</th>
</tr>
<tr v-for="item in studentList" :key="item.sid">
<td>{{item.sid}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>
<a href="" @click.prevent="deleteStudent(item.sid)">删除</a>
</td>
<td>
<router-link :to="{path:'/EditStudent',query:{id:item.sid}}">修改</router-link>
</td>
</tr>
</table>
</template>
<script>
export default{
name:"students",
data:function(){
return{
studentList:[]
}
},
methods:{
getStudents:function(){
this.$axios.get("http://localhost:8080/student").then(res=>{
this.studentList = res.data;
console.log(res.data)
})
},
deleteStudent:function(sid){
this.$axios.delete("http://localhost:8080/student/"+sid).then(res=>{
if(res.data == 1){
window.alert("删除成功");
this.getStudents();
}
})
}
},
mounted:function(){
this.getStudents();
}
}
</script>
AddStudent.vue
<template>
<div>
<pre>
学生id: <input type="text" v-model="student.sid">
学生姓名: <input type="text" v-model="student.name">
学生年龄: <input type="text" v-model="student.age">
<input type="button" @click="add()" value="添加">
</pre>
</div>
</template>
<script>
EditStudent.vue
<template>
<pre>
学生id: <input type="text" readonly v-model="student.sid">
学生姓名: <input type="text" v-model="student.name">
学生年龄: <input type="text" v-model="student.age">
<input type="button" @click="fix()" value="修改">
</pre>
</template>
<script>
export default{
name:"EditStudent",
data:function(){
return{
student:{
sid:"",
name:"",
age:""
}
}
},
methods:{
getStudentById:function(id){
this.$axios.get("http://localhost:8080/student/"+id).then(res=>{this.student=res.data})
},
fix:function(){
this.$axios.post("http://localhost:8080/student",this.$qs.stringify(this.student)).then(res=>{
if(res.data == 1){
this.$router.push("/")
}
})
}
},
mounted:function(){
var id = this.$route.query.id;
this.getStudentById(id);
}
}
</script>
router. - >index.js
import { createRouter, createWebHashHistory } from "vue-router";
// import Home from "../views/Home.vue";
const 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"),
// },
{
path:"/",
name:"Student",
component:()=>
import("../views/Students.vue")
},
{
path:"/EditStudent",
name:"EditStudent",
component:()=>import("../views/EditStudent.vue")
},
{
path:"/AddStudent",
name:"AddStudent",
component:()=>import("../views/AddStudent.vue")
}
];
const router = createRouter({
history: createWebHashHistory(),
routes,
});
export default router;
main.js
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
// 导入 axios
import axios from "axios";
import qs from "qs";
// 配置全句访问
var app =createApp(App);
app.config.globalProperties.$axios = axios;
app.config.globalProperties.$qs = qs;
app.use(store).use(router).mount("#app");