vue时一套前端框架,免除原生JavaScript中的DOM操作,简化书写
基于MVVM(Model-View-View-Model)思想,实现数据的双向绑定,将编程的关注点放在数据上
官网:<https://v2.cn.vuejs.org>根据提示下载好vue.js文件
> 框架:是一个半成品软件,是一套可重用的、通用的、软件基础代码模型。基于框架开发更加快捷、高效。
<!-- 入门代码 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue快速入门</title>
<script src="./js/vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="message"/>
{{message}}
</div>
</body>
<script>
//定义Vue对象
new Vue({
el:"#app",//类似于css的选择器,指定Vue接管的内容
data:{
message:"hello vue"
}
})
</script>
</html>
{{插值表达式}}
是一种特殊的语法,用于将数据动态地插入到HTML模板中。
常用指令
指令:HTML标签上带有v-前缀的特殊属性,不同指令具有不同含义。
常用的指令:
指令 | 作用 |
---|---|
v-bind | 为HTML标签绑定属性值,如设置href、css样式等 |
v-model | 在表单元素上创建双向数据绑定 |
v-on | 为HTML标签绑定事件 |
v-if\v-else-if\v-else | 条件性的渲染某元素,判定为true时渲染,否则不渲染 |
v-show | 根据条件展示某元素,区别在于切换的是display属性的值 |
v-for | 列表渲染,遍历容器的元素或者对象的属性 |
- - v-bind
`<a v-bind:href="url">百度</a>`
`<a :href="url">百度</a>`
- - v-model
`<input type="text" v-model="url">`
<script>
new Vue({
el:'#id',
data:{
url:"https://baidu.com"
}
})
</script>
通过v-bind或者v-model绑定的变量必须在数据模型中声明
- v-on
- v-if:根据条件的真值决定是否渲染元素
年龄{{age}},经判定为
<span v-if="age <= 35">年轻人</span>
<span v-else-if="age>35 && age<60">中年人</span>
<span v-else>老年人</span>
- v-show:控制css的display属性来控制元素是展示还是隐藏的(都渲染)
年龄{{age}}
<span v-show="age<=35">年轻人</span>
<!--如果不满足条件,则实际就变为-->
<span v-show="age>35" style="display:none;">中年人</span>
- v-for
一个小案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue案例</title>
<script src="./js/vue.js"></script>
</head>
<body>
<table id="biaoge" align="center">
<thead align="center">
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>成绩</th>
<th>等级</th>
</tr>
</thead>
<tbody v-for="(user,index) in users" align="center">
<tr>
<td>{{index+1}}</td>
<td>{{user.name}}</td>
<td>{{user.age}}</td>
<td v-if="user.gender==1">男</td>
<td v-else>女</td>
<td>{{user.score}}</th>
<td v-if="user.score>=85">优秀</td>
<td v-else-if="user.score<85 && user.score>=60">及格</th>
<td v-else><font color=red>不及格</font></td>
</tr>
</tbody>
</table>
</body>
<script>
new Vue({
el:"#biaoge",
data:{
users:[
{
name:"Winnie",
age:19,
gender:2,
score:100
},{
name:"Iris",
age:20,
gender:2,
score:72
},{
name:"Jerry",
age:26,
gender:1,
score:61
},{
name:"Tony",
age:30,
gender:2,
score:52
}
]
}
})
</script>
</html>
输出结果:
生命周期
指一个对象从创建到销毁的整个过程
vue对象生命周期的八个阶段:每触发一个生命周期事件会自动执行一个生命周期方法(钩子)
状态 | 阶段周期 |
---|---|
beforeCreate | 创建前 |
created | 创建后 |
beforeMount | 挂载前 |
mounted | 挂载完成 |
beforeUpdate | 更新前 |
updated | 更新后 |
beforeDestroy | 销毁前 |
destroyed | 销毁后 |
<script>
new Vue({
el:"#yanshi",
data:{},
mounted(){
// 通常用于发送请求到服务端获取数据
alert("vue挂载完成")
},
methods:{}
})
</script>