Vue基础

Vue基本知识

1、vue的第一个入门应用

基本框架

<!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>基本框架</title>
</head>

<body>
    <div id="app">

    </div>
</body>

</html>
<script type="text/javascript" src="https://unpkg.com/vue"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            
        },
        methods: {
        }
    });
</script>
  • 导入vue
    • 1.下载
    • 2.cdn方式,此处采用cdn
<script type="text/javascript" src="https://unpkg.com/vue"></script>
  • 创建Vue实例
<script>
    // 实例化vue对象
    new Vue({
        el: "#app", //作用域
        data: {
            msg: "hello vue", //数据
        }
    });
</script>
  • 通过{{}}引用数据
{{msg}}
<h1 v-text="msg"></h1>
<h1 v-html="msg"></h1>

2、v-text与v-html

        <h1 v-text="content"></h1>
        <h1 v-html="content"></h1>

总结

  • {{}}(插值表达式)和v-text获取数据的区别在于

    • 使用v-text取值会将标签中原有的数据覆盖,使用插值表达式不会覆盖原有数据
    • 使用v-text可以避免在环境较差时候的差值闪烁
  • v-html和v-text的区别:

    • v-text不会解析html标签,而v-html会解析html标签

3、v-on:(简写@)

事件的三要素:事件源(html元素)、事件(发生的时间)、监听器(函数处理)

js绑定事件

        <button onclick="text()">html中的按钮</button>
      	<script>
            function text() {
                alert("html")
            }
        </script>

vue-on绑定事件

		<!--鼠标点击 和鼠标移入两个事件    语法:v-on:(事件)="监听函数名(有参数要加上括号,没参数可以直接写函数名)"-->
		<button v-on:click="text" @mouseover="text1">vue中的按钮</button>
        <script>
            new Vue({
                el: "#app",
                data: {
                    msg: "hello vue",
                    count: 0,
                },
                methods: {
                    text: function () {
                        this.count++;
                    },
                    text1: function () {
                        console.log("鼠标移入");
                    }
                }
            });
        </script>

总结:

  • 事件三要素

    • 事件源:发生事件的dom元素
    • 事件:发生特定的动作
    • 监听器:发生特定动作之后的时间处理程序 通常是js函数
  • 在Vue中绑定事件是通过v-on指令来完成的,v-on:事件名 如:v-on:click

  • 在v-on:事件名的赋值语句中是当前事件触发调用的函数名

  • 在Vue中事件的函数统一定义在Vue实例的methods属性中

  • 在Vue定义的事件中this指的就是当前的Vue实例,日后可以在事件中通过使用this获取Vue实例中得相关数据

  • 在Vue中绑定事件时可以通过@符号形式,简化v-on的事件绑定 例如@click="text3()=v-on:click=“text()”

4、v-if与v-show

<body>
    <div id="app">
        <h1 v-if="isShow">{{msg}}</h1>
        <h1 v-show="isShow">{{msg}}</h1>
    </div>
</body>

</html>
<script type="text/javascript" src="https://unpkg.com/vue"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            msg: "v-if",
            msg1: "v-show",
            isShow: false,
        },
        methods: {
        }
    });
</script>

总结

  • 作用:通过vue方式控制页面中的那些标签显示或隐藏

  • 语法:v-if|v-show=“ture|false”

  • 区别:
    1.v-if:底层通过dom树上的元素节点实现标签的展示和隐藏 dom树
    2.v-show:底层通过控制CSS中的display属性实现标签的展示和隐藏 css样式

  • 总结:
    一般来说,v-if有更高的切换开销,而v-show有更高的初始渲染开销。
    因此,如果非常频繁的切换,使用v-show较好;变化快 用v-show ;变化慢,用v-if

5、v-bind:(简写:)

<body>
    <div id="app">
        <div v-bind:class="st" @mouseover="st='aa'" @mouseout="st='bb'">
        </div>
    </div>
</body>

<style>
    .aa {
        width: 200px;
        height: 200px;
        border: solid 10px red;
    }

    .bb {
        width: 200px;
        height: 200px;
        border: dashed 10px green;
    }
</style>
<script type="text/javascript" src="https://unpkg.com/vue"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            st:"aa"
        },
        methods: {

        }
    });
</script>

总结

  • 作用:用来将html标签属性绑定vue实例,以后可以通过修改vue事例中的属性达到动态修改标签属性

  • 语法 v-on:属性名=“属性值” 或者:属性名=“属性值”

6、v-for

<body>
    <div id="app">

        <!-- 遍历对象 -->
        <span v-for="value,key,index in user">
            [{{index}} {{key}} {{value}}] 
        </span>

        <!-- 遍历数组 -->
        <ul>
            <li v-for="item,index in school">
                {{index+1}} {{item}}
            </li>
        </ul>

        <!-- 遍历数组中的对象 -->
        <table width="100%" border="1">
            <tr>
                <th>序号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>性别</th>
            </tr>
            <tr v-for="item,index in users" key="index">
                <td>{{index+1}}</td>
                <td>{{item.name}}</td>
                <td>{{item.age}}</td>
                <td>{{item.sex}}</td>
            </tr>
        </table>
    </div>
</body>

</html>
<script type="text/javascript" src="https://unpkg.com/vue"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            users:[{ name: "morant", age: "20", sex: "男" }, { name: "tomyoung", age: "20", sex: "男" }, { name: "zm", age: "20", sex: "男" }],
            user:{name:"morant",age:"20",sex:"男"},
            school:["东校区","西校区","总部"]
        },
        methods: {
        }
    });
</script>

总结:

  • 作用:用来在页面中实现vue中定义数据的遍历(遍历 对象、数组)

  • 语法:直接在对象标签上加上v-for

    • 遍历对象: v-for=“value,key,index in data中的变量名”
    • 遍历数组: v-for=“item,index in data中的变量名”
    • 遍历数组对象: v-for=“item(对象),index in data中的变量名”
  • 注意: 在使用v-for时,建议就可能的绑定key属性 :key(key属性唯一)

7、v-model

<body>
    <div id="app">
        <form action="">
            用户名<input type="text" v-model="user.username">
            密码<input type="text" v-model="user.password">
            邮箱<input type="text" v-model="user.email">
            电话<input type="text" v-model="user.phone">
            <input type="button" value="提交" @click="con()">
        </form>
    </div>
</body>

</html>
<script type="text/javascript" src="https://unpkg.com/vue"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            user:{},
        },
        methods: {
            con:function(){
                console.log("用户名:"+this.user.username);
                console.log("密码:" + this.user.password);
                console.log("邮箱:" + this.user.email);
                console.log("电话:" + this.user.phone);
            }
        }
    });
</script>

总结:

  • v-bind: 绑定
    • 作用: 用来将html标签的属性进行绑定,交给vue实例管理,除了value属性以外的所有属性
  • v-model 模型
    • 作用: 用来将html标签的value属性进行绑定,交给vue实例管理 主要在表单元素上
    • 语法: 在表单元素上直接加入v-model=“vue事例中的一个变量”

8、记事本案例

<body>
    <div id="app">
        请输入内容<input type="text" v-model="content"><button @click="add(content)">添加到备忘录</button><br>
        <ul>
            <li v-for="item,index in noforget">{{index+1}} {{item}}<a href="javascript:;" @click="del(index)">删除</a></li>
        </ul>
        <a href="javascript:;" @click="delall">清空备忘录</a>
        <span>备忘录共{{}}条</span>

    </div>
</body>

</html>
<script type="text/javascript" src="https://unpkg.com/vue"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            content:"",
            noforget:[],
        },
        methods: {
            add(content){
                if(content){
                    this.noforget.push(content);
                    this.content="";
                }
            },
            del(index){
                this.noforget.splice(index);
            },
            delall(){
               this.noforget=[];
            },
        }
    });
</script>

总结

  • 当文本内容为“”或者null时,if(content)中的布尔值都为false

  • 当a标签用来当按钮是,href中可以填"javascript:;"

  • 方法:

    • 往数组末尾增加元素用push()
    • 删除数组指定下标的元素用splice(index,number):从指定位置开始删除,一共删除number个

9、购物车案例

<body>
    <div id="app">
        <h1>购物车案例</h1>
        <table border="1">
            <tr>
                <th>编号</th>
                <th>名称</th>
                <th>价格</th>
                <th>购买数量</th>
                <th>小计</th>
            </tr>
            <tr v-for="(item,index) in list">
                <td>{{item.id}}</td>
                <td>{{item.name}}</td>
                <td>{{item.price}}</td>
                <td>
                    <button @click="sub(index)">-</button>
                     &nbsp;{{item.number}}&nbsp;
                    <button @click="add(index)">+</button>
                </td>
                <td>{{(item.price*item.number).toFixed(2)}}</td>
            </tr>
        </table>
        <span>总计:{{toTotalprice()}}元</span>
    </div>
</body>

</html>
<script type="text/javascript" src="https://unpkg.com/vue"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            list:[
                { id: 1, name: "苹果", price: 1.1, number: 0, total: 0 },
                { id: 2, name: "香蕉", price: 1.2, number: 0, total: 0 },
                { id: 3, name: "菠萝", price: 1.3, number: 0, total: 0 },
            ],
        },
        methods: {
            add(index){
                this.list[index].number++;
                console.log(this.list)
            },
            sub(index) { 
                if(this.list[index].number!=0){
                    this.list[index].number--;
                }
            },
            toTotalprice(){
                var price=0;
                for(var i=0;i<this.list.length;i++){
                    price= price+ this.list[i].price * this.list[i].number;
                }
                return price.toFixed(2);
            }
        }
    });
</script>

总结

  • toFixed(2)可以保留两位小数
  • 可以通过computed{}属性来计算,提高vue的性能

10、事件修饰符

  • .stop:用来阻止事件冒泡
  • prevent:用来阻止标签的默认行为(例如a标签的点击跳转页面和单击事件)
  • self:只监听自身标签触发的事件
  • once:该事件指出发一次
  • 语法:@事件名.事件修饰符=“事件处理函数”===>@click.stop=“test”

11、按键修饰符

只能对键盘上的按键事件进行修饰 修饰符

.enter 对键盘回车键修饰

.tab 对键盘切换tab按键修饰

.delete (捕获"删除"和"退格"键)

.space 对键盘的空格按键修饰

.esc 对键盘的esc按键修饰

.up 上

.down 下

.left 左

.right 右

例子:@keyup.enter=“test”

12、axios

1、简介

axios 前端异步请求库,类似jQuery的ajax技术,用啦在前段页面发起一个异步请求,请求之后页面不动,响应回来刷新页面布局

官方定义:易用、简洁且高效的http库==>发送http异步请求库

特性:

  • 从浏览器中创建XMLHttpRequests

  • 从node.js创建http请求

  • 支持Promise API

  • 拦截请求和响应(重点)

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

  • 取消请求

  • 自动转换JSON数据(重点)

  • 客户端支持防御XSRF

2、axios的基本使用

a.下载核心js文件

​ https://unpkg.com/axios@0.21.1/dist/axios.min.js

b.页面引入axios核心js文件

<script src="js/axios.min.js"></script>

c.发送异步请求

  • 发送GET请求(格式:axios.get(function(success){return success}).then.catch(function(err){return err}))
<script>
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 可选地,上面的请求可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
</script>
  • 发送post请求 axios.post(function(success){return success}).then.catch(function(err){return err}))
<script>
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
</script>
  • 等等

3、创建默认实例发送请求

<script>
	//创建axios的配置对象
    var instance = axios.create({
        baseURL:"http//localhost:8081/",
        timeout:5000
    });
    //发送get方式请求
    instance.get("/demo?id=11&name=xiaochen").then(function(res){
        console.log(res.data);
    }).catch(function(err){
        console.log(err);
    })
</script>

4.axios中的拦截器

1.拦截器 interceptor

作用:用来将axios的公有参数,响应公共处理交给拦截器处理,减少axios发送请求代码的冗余

2.axios拦截器类型

​ a.请求拦截器

instance.interceptors.request.use(function(config){
	if(config.url.indexOf("?")==-1){
		config.url+="token=1234";
	}else{
		config.url+="&token=1234"
	}
	return config;
})

​ b.响应拦截器

instance.interceptors.response.use(function(response){
	console.log("进入响应拦截器",response);
	if(response.status==500){
		alert("服务器出现错误")
	}
	return response;
})

13、生命周期(重要)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ay0l3cN1-1632559373891)(https://v3.cn.vuejs.org/images/lifecycle.svg)]

<!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>基本框架</title>
</head>

<body>
<div id="app">
    <h1 id="h1">{{msg}}</h1>
    <input type="text" v-model="msg">
</div>
</body>
</html>
<script type="text/javascript" src="https://unpkg.com/vue"></script>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            msg:"Vue生命周期"
        },
        methods:{},
        computed:{},
        //初始化阶段
        beforeCreate(){//初始化阶段第一个生命周期函数,这个函数执行时,仅仅完成自身内部事件和生命周期函数注入
            console.log("beforeCreate msg",this.msg);
        },
        created(){//初始化阶段第二个生命周期函数,这个函数执行时,完成自身内部事件和生命周期函数注入 包括自定义data、methods、computed等属性注入和校验
            console.log("created msg",this.msg);
        },
        beforeMount(){//初始化阶段第三个生命周期函数,这个函数执行时,el执行html还是一个模板,并没有完成数据渲染工作
            console.log("beforeMount",document.getElementById("h1").innerText);
        },
        mounted(){//初始化阶段第四个生命周期函数,这个函数执行时,vue已完成templete和el执行html工作
            console.log("mounted",document.getElementById("h1").innerText);
        },
        //运行阶段
        beforeUpdate(){//运行阶段第一个函数,这个函数执行时,data数据发生变化,此时页面还是原数据
            console.log("beforeUpdate msg",this.msg);
            console.log("beforeUpdate",document.getElementById("h1").innerText);
        },
        updated(){//运行阶段第二个函数,这个函数执行时,data数据和页面数据保持一致
            console.log("update msg",this.msg);
            console.log("update",document.getElementById("h1").innerText);

        },
        //销毁阶段
        beforeDestroy(){//销毁阶段第一个函数,这个函数执行时,vue实例刚刚开始销毁
            console.log("开始销毁");
        },
        destroyed(){//销毁阶段第二个函数,这个函数执行时,vue实例全部销毁
            console.log("全部销毁");
        },
    });
</script>

总结:

  • 初始化阶段

    • beforeCreate:这个函数执行时,仅仅完成自身内部事件和生命周期函数注入
    • created:这个函数执行时,完成自身内部事件和生命周期函数注入 包括自定义data、methods、computed等属性注入和校验
    • beforeMount:这个函数执行时,el执行html还是一个模板,并没有完成数据渲染工作
    • mounted:这个函数执行时,vue已完成templete和el执行html工作
  • 运行阶段

    • beforeUpdate:这个函数执行时,data数据发生变化,此时页面还是原数据
    • updated:这个函数执行时,data数据和页面数据保持一致
  • 销毁阶段

    • beforeDestroy:这个函数执行时,vue实例刚刚开始销毁
    • destroyed:这个函数执行时,vue实例全部销毁

14、ES6语法

1、变量声明:

var 原因:使用var声明变量存在作用范围混淆问题

let:用来声明局部变量。 好处:作用范围严谨,从代码块声明初开始,到代码快结束。

const:用来声明js中常量(对象,数组) 好处:一旦被赋值不能被修改(只是变量地址不被修改。

2、匿名函数

在使用匿名函数时。function(){} 推荐使用es6中箭头函数 (参数)=>{函数体}

1.当箭头函数没有参数时或者参数大于1个,必须加入()

2.当箭头函数只有一个参数时()可以省略不写

3.当函数体中只有一行代码时,函数体{}可以省略不写

3、模板字符串

适用于法``

   let html = `<div>
                    <h1>ES6模板语法</h1>
                </div>`

4、对象定义

在定义对象时如果对象属性名和变量名一致,写一个即可。

const emp = {id,name,age}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MMorant

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值