Vue框架的使用方法(三)

525 阅读6分钟

Vue框架

Vue是什么

​ Vue是渐进式Js框架,主要用于外部式JS文件。作者尤雨溪。**Vue官网地址:**cn.vuejs.org/

使用Vue写一个HelloWorld

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello world Vue!</title>
</head>
<body>
<div id="my" style="text-align: center;color: burlywood;background-color: black">
{{text}}
</div>
</body>
<!--导入Vue.js-->
<script type="text/javascript" src="../js/vue.min.js"></script>

<script type="text/javascript">
  new Vue({
    el:"#my",
    data:{
      "text":"hello world"
    }
  });
</script>
</html>

注意

1.一般一个Vue对象,对应一个挂载点。挂载点一般使用id设置。

2.Vue对象中属性是固定值,如el、data、methods等,属性值是可变的。

3.Vue环境中的挂载点位置,实际上是html和js结合代码。

4.Vue中一般使用两种语法绑定数据。

(1)插入绑定

语法:

{{}}

(2)指令绑定

v-bind:value
v-model:value
/*以及其他指令..*/

Vue的单向绑定和双向绑定

单向绑定

语法:

(1)标准语法:

v-bind:value

(2)简写语法:

:value

作用:将Vue对象中的数据流向挂载点中。

适用场景:绑定表单中value属性值。

示例:

<div id = "context">
   用户名1:<input type="text" name="userName" v-bind:value="un" value="sss"><br>
     用户名2:<input type="text" name="userName" :value="un" value="sss"><br>
</div>
var vm = new Vue({
    el:"#context",
    data:{
        "un":"zhangsan"
    }
});

双向绑定

语法:

(1)标准语法:

v-model:value

(2)简写语法:

v-model

作用:将Vue对象中数据流向至挂载点,反向,将挂载点中数据流向Vue对象中。

示例:

<div id = "app">
    邮箱1:<input type="text" name = "email" v-model:value="email"><br>
    邮箱2:<input type="text" name = "email" v-model="email"><br>
    结果:{{email}}
</div>
new Vue({
    el:"#app",
    data:{
        "email":"test@163.com"
    }
});

v-bind和v-model的区别:

​ v-model只能用在表单类标签(用户输入类元素)上、比如说input,select等等。

指定挂载点的第二种写法(.$mount)

写在括号外部

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Hello world Vue!</title>
</head>
<body>
<div id="my" style="text-align: center;color: burlywood;background-color: black">
{{text}}
</div>
</body>
<!--导入Vue.js-->
<script type="text/javascript" src="../js/vue.min.js"></script>

<script type="text/javascript">
const app = new Vue({
 // el:"#my",//第一种写法
 data:{
   "text":"hello world"
 }
});
//设置挂载点,第二种方法
app.$mount('#my');
</script>
</html>

这两种方式都可以,$mount这一种方式更灵活,比如说指定完里面的数据data而没有立即指定挂载点,而是写了若干行代码后才指定挂载点,所以data加载到挂载点需要若干时间。

data的第二种写法:函数式

//data的两种写法
		new Vue({
			el:'#my',
			//data的第一种写法:对象式
			/*  data:{
 		  text:"hello world"
 	} */
 
			//data的第二种写法:函数式
			data(){
				console.log(this) //此处的this是Vue实例对象 如果使用箭头函数this将指向window代码将会出错
				return{
					text:"hello world"
				}
			}
		});

绑定样式表

语法:

(1)标准语法

v-bind:class

(2)简写语法

:class

作用:动态绑定样式表

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .classA{
            /*背景颜色*/
            background-color: hotpink;
        }
        .classB{
            /*文本颜色*/
            color: skyblue;
        }
        .classC{
            /*字体大小*/
            font-size: 80px;
        }
    </style>
</head>
<body>
    <div id="app">
        <p class="classA classB">段落一</p>
        <p v-bind:class="{classA:isA,classB:isB}">段落2</p>
        <p :class="{classA:isA,classB:isB}">段落3</p>
    </div>
</body>
<script type="text/javascript" src="../js/vue_v2.6.14.js"></script>
<script type="text/javascript">
    new Vue({
        el:"#app",
        data:{
            "isA":false,
            "isB":true
        }
    });
</script>

Vue条件渲染

(1)if...else

语法:

v-if
v-else

特点:当条件是true时,只显示if中的数据,条件时false只显示else中的数据【如果不显示数据的话,也就不加载这段代码,因为js是边解释边执行】

(2)show

语法

v-show

特点:当条件为true时显示数据,条件为false时隐藏数据【display:none】

(3)示例

<body>
    <div id="app">
        <p v-if="bool">段落一</p>
        <p v-else="bool">段落二</p>
        <p v-show="bool">段落三</p>
    </div>
</body>
<script type="text/javascript" src="../js/vue_v2.6.14.js"></script>
<script type="text/javascript">
    new Vue({
        el:"#app",
        data:{
            "bool":true
        }
    });
</script>

Vue中的列表渲染

语法:

v-for="数据遍历名 in 数据组名"

在使用时,调用我们自定义的数据遍历名。

作用:渲染列表

示例代码

<body>
    <div id="context">
        <ul>
            <li v-for="stuName in stuNameList">{{stuName}}</li>
        </ul>
        <table border="1" width="500px" height="300px">
            <tr>
                <th>学生学号</th>
                <th>学生性别</th>
                <th>学生年龄</th>
                <th>学生性别</th>
            </tr>
            <tr align="center" v-for="(student,index) in studentList">
                <td>{{index}}</td>
                <td>{{student.stuName}}</td>
                <td>{{student.stuAge}}</td>
                <td>{{student.stuGender}}</td>
            </tr>
        </table>
    </div>
</body>
<script type="text/javascript" src="../js/vue_v2.6.14.js"></script>
<script type="text/javascript">
    new Vue({
        el:"#context",
        data:{
            "stuNameList":[
                "guoqiang888",
                "xiudong777",
                "zhenhua666"
            ],
            "studentList":[
                {"stuName":"guoqiang","stuAge":18,"stuGender":"男"},
                {"stuName":"xiudong777","stuAge":19,"stuGender":"男"},
                {"stuName":"zhenhua666","stuAge":20,"stuGender":"男"},
            ]
        }
    });
</script>

Vue的事件驱动

语法:

①标准语法

v-on:事件名

②简写语法

@事件名

示例代码

<body>

    <div id="app">
        <form action="target.html" method="post">
            用户名:<input @blur="checkUserName" v-model="uname" type="text" name="username">
                    <span>{{userNameMsg}}</span>
            <br>
            <!--事件驱动-->
            密码:<input @blur="checkPwd" v-model="password" type="password" name="pwd">
                    <span>{{pwdMsg}}</span>
            <br>
            <input type="submit" @click="checkLogin" value="登录">
        </form>
    </div>

</body>
<script type="text/javascript" src="../js/vue_v2.6.14.js"></script>
<script type="text/javascript">
    // 失去焦点时,验证用户名不能为空
    var vm = new Vue({
        el:"#app",      //设置挂载点
        data:{          //设置绑定数据
            // "uname":this
            //双向绑定,获取数据
            "uname":"",
            "password":"",
            //插值绑定,提示信息
            "userNameMsg":"",
            "pwdMsg":""
        },
        methods:{       //设置关联函数
            checkUserName:function(){
                this.userNameMsg = "";
                // console.log("加号this:"+this);
                // console.log("逗号this:",this);
                // console.log("uname:",vm.uname);
                if(vm.uname == ""){
                    this.userNameMsg = "用户名不能为空,请重新输入#####";
                    //取消控件默认行为
                    event.preventDefault();
                }
            },
            checkPwd(){
                // console.log("this:",this);
                this.pwdMsg = "";
                if(this.password == ""){
                    this.pwdMsg = "密码不能为空,请重新输入!";
                    //取消控件默认行为
                    event.preventDefault();
                }
            },
            checkLogin(){
                // checkUserName(); //错误的
                this.checkUserName();
                this.checkPwd();
                /*
                if(this.uname == ""){
                    // alert("用户名不能为空,请重新输入#####");
                    this.userNameMsg = "用户名不能为空,请重新输入#####";
                    //取消submit控件默认行为
                    // return false;  //在Vue中无效写法
                    // alert("event:",event);
                    event.preventDefault();
                }
                 */
            }

        }
    });

</script>

Vue的事件函数写在什么地方?

​ methods:后的大括号里头,多个事件函数之间用逗号“,”隔开。注意这里的函数名要与html中写的触发事件函数名一致。格式是 事件名:function(参数){方法体} 或者 事件名(参数):{方法体}。

html中写的函数如果没有参数可以去掉括号简写。

怎么知道文本框里是空的?

​ 此处使用了v-model双向绑定,那么vue对象也可以接收到页面中穿过来的数据。在事件驱动中想要获得数据就直接Vue对象名.接收了值的变量名,就可以得到数据了。由于在方法中的this指代的是Vue对象,所以我们也可以写为this.接收了值的变量名。

怎么阻止表单提交?

​ 在没有使用Vue时(比如说表单的属性中,Js中Vue外),我们可以在函数中使用return false来阻止表单提交,但是由于Vue使用了特殊的方式关联到了事件中,return false失效了,不能使用它来阻止表单提交。此处Vue使用了**event.preventDefault();**方法,阻止事件的默认方法。

console.log与alert方法的使用说明。

​ 在console.log方法中如果使用加号+,如果前后数据类型不一致,就会变成字符串拼接输出,如果都是数据类型,那么就进行加法运算;如果使用的是逗号,,那么就默认都是字符串,然后在逗号的地方加上一个空格输出。

​ 在alert中,只能使用加号(与console.log的用法相同)。不支持逗号,如果遇到逗号就结束了,第一个逗号之后的内容不会输出。

怎么调用其他自定义方法?

不能直接调用,要使用“this.方法名”

Vue的this关键字

JS中的this

①在函数外面的this:

​ 指向window对象(代表当前浏览器窗口)。

②在函数里面的this:

​ 指向调用这个函数的对象。

在JS里,this关键字是可变的,JS的this指向是不确定的,也就是说是可以动态改变的。call/apply 就是用于改变this指向的函数,这样设计可以让代码更加灵活,复用性更高。

Vue中的this

①在methods区域函数外边的this:

​ 指向window对象(代表当前浏览器窗口)。

②在methods区域函数里面的this:

​ 指向它所在的Vue对象

Event(事件)对象

定义

​ Event对象代表事件的状态,比如事件在其中发生的元素、键盘按键的状态、鼠标的位置、鼠标按钮的状态。

常用属性

​ target:返回出发此事件的元素(事件的目标节点)。

常用方法

​ preventDefault():取消控件默认行为。【通知浏览器不要执行与事件关联的默认动作】

​ stopPropagation():取消事件冒泡。【不再派发事件】

Vue的侦听属性——"watch"属性

​ 这个是用来侦听事件,发现某个事件发生了就调用我们编写好的函数。

比如说:

<div id="app">
	<p>尊姓:{{firstName}}</p>
	<p>大名:{{lastName}}</p>
	尊姓:<input type="text" v-model="firstName" /><br/>
	大名:<input type="text" v-model="lastName" /><br/>
	<p>全名:{{fullName}}</p>
</div>

​ 在上面代码的基础上,我们希望firstName或lastName属性发生变化时,修改fullName属性。此时需要对firstName或lastName属性进行『侦听』。

​ 具体来说,所谓『侦听』就是对message属性进行监控,当firstName或lastName属性的值发生变化时,调用我们准备好的函数。

​ 那么我们就可以使用Vue在watch属性中声明对firstName和lastName属性进行『侦听』的函数如下所示:

var app = new Vue({
	el:"#app",
	data:{
		"firstName":"jim",
		"lastName":"green",
		"fullName":"jim green"
	},
	watch:{
		"firstName":function(inputValue){
			this.fullName = inputValue + " " + this.lastName;
		},
		"lastName":function(inputValue){
			this.fullName = this.firstName + " " + inputValue;
		}
	}
});

Vue的生命周期

程序中的生命周期概念:指的是对象从创建到销毁的过程。

Vue生命周期概述

①创建对象

​ Ⅰ创建对象之前【beforedCreate】

​ Ⅱ创建对象之后【created】

②数据挂载

​ Ⅰ数据挂载之前【beforeMount】

​ Ⅱ数据挂载之后【Mounted】

③数据更新

​ Ⅰ数据更新之前【beforeUpdate】

​ Ⅱ数据更新之后【updated】

④销毁对象

​ Ⅰ销毁对象之前【beforeDestroy】

​ Ⅱ销毁对象之后【destroyed】