Vue笔记 - [入门&指令]
vue是什么?
- Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架
- vue 的核心库只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合
入门
通过CDN引入
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
通过本地JS文件引入
<script src="vue.js路径"></script>
入门代码
<div id="app">
<h1>{{msg}}</h1>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
msg: 'Hello Vue!'
}
})
</script>
- el : 元素的挂载位置(值可以是CSS选择器或者DOM元素)
- data : 模型数据(值是一个对象)
- 插值表达式({{}}):
- 将数据填充到HTML标签中
- 插值表达式支持基本的计算操作
指令
- 本质就是自定义属性
- Vue中指定都是以 v- 开头
v-cloak
-
防止页面加载时出现闪烁问题
<div id="app"> <h1 v-cloak>{{msg}}</h1> </div> <script> let app = new Vue({ el: '#app', data: { msg: 'Hello Vue!' } }) </script> <style scope> [v-cloak]{ /* 元素隐藏 */ display: none; } </style>
v-text
- v-text指令用于将数据填充到标签中,作用于插值表达式类似,但是没有闪动问题
- 如果数据中有HTML标签会将html标签一并输出
- 注意:此处为单向绑定,数据对象上的值改变,插值会发生变化;但是当插值发生变化并不会影响数据对象的值
<div id="app">
<h1 v-text="msg"></h1>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
msg: 'Hello Vue!'
}
})
</script>
v-html
-
用法和v-text 相似 但是他可以将HTML片段填充到标签中
-
可能有安全问题, 一般只在可信任内容上使用
v-html
,永不用在用户提交的内容上 -
它与v-text区别在于v-text输出的是纯文本,浏览器不会对其再进行html解析,但v-html会将其当html标签解析后输出。
<div id="app">
<div v-html="msg"></div>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
msg: '<h1>Hello Vue!</h1>'
}
})
</script>
v-pre
-
显示原始信息跳过编译过程
-
跳过这个元素和它的子元素的编译过程。
-
一些静态的内容不需要编译加这个指令可以加快渲染
<div id="app"> <h1 v-pre>{{msg}}</h1> </div> <script> let app = new Vue({ el: '#app', data: { msg:'Hello World!' } }) </script>
v-once
-
执行一次性的插值【当数据改变时,插值处的内容不会继续更新】
<div id="app"> <h1 v-once>{{msg}}</h1> </div> <script> let app = new Vue({ el: '#app', data: { msg: 'Hello Vue.js' } }) </script>
双向数据绑定
- 当数据发生变化的时候,视图也就发生变化
- 当视图发生变化的时候,数据也会跟着同步变化
v-model
-
v-model是一个指令,限制在
<input>、<select>、<textarea>、components
中使用<div id="app"> <h1>{{msg}}</h1> <!-- 当输入框中内容改变的时候, 页面上的msg 会自动更新 --> <input type="text" v-model="msg"> </div> <script> let app = new Vue({ el: '#app', data: { msg: 'Hello Vue!' } }) </script>
mvvm
- MVC 是后端的分层开发概念; MVVM是前端视图层的概念,主要关注于 视图层分离,也就是说:MVVM把前端的视图层,分为了 三部分 Model, View , VM ViewModel
- m model
- 数据层 Vue 中 数据层 都放在 data 里面
- v view 视图
- Vue 中 view 即 我们的HTML页面
- vm (view-model) 控制器 将数据和视图层建立联系
- vm 即 Vue 的实例 就是 vm
v-on
-
用来绑定事件的
-
形式如:v-on:click 缩写为 @click;
<div id="app"> <h1>{{msg}}</h1> <button type="button" v-on:click="msg++">点击</button> <button type="button" @click="msg++">点击1</button> <button type="button" @click="handle">点击2</button> </div> <script> let app = new Vue({ el: '#app', data: { msg: 0 },methods:{ handle:function () { this.msg++; } } }) </script>
-
事件函数的调用方式:
-
直接绑定函数名称
<button v-on:click='say'>Hello</button>
-
调用函数
<button v-on:click='say()'>Say hi</button>
-
-
事件函数 - 参数传递
<div id="app"> <h1>{{msg}}</h1> <!-- 如果事件直接绑定函数名称,那么默认会传递事件对象作为事件函数的第一个参数 --> <button v-on:click='handle1'>点击1</button> <!-- 2、如果事件绑定函数调用,那么事件对象必须作为最后一个参数显示传递, 并且事件对象的名称必须是$event --> <button type="button" @click="changeMsg('你好Vue!',$event)">点我改变</button> </div> <script> let app = new Vue({ el: '#app', data: { msg: 'Hello Vue!' }, methods:{ handle1: function (event) { console.log(event.target.innerHTML); }, changeMsg:function (message,event) { this.msg = message; console.log(event.target.innerHTML); } } }) </script>
事件修饰符
- 在事件处理程序中调用
event.preventDefault()
或event.stopPropagation()
是非常常见的需求。 - Vue 不推荐我们操作DOM 为了解决这个问题,Vue.js 为
v-on
提供了事件修饰符 - 修饰符是由点开头的指令后缀来表示的
<!-- 阻止单击事件继续传播 -->
<a v-on:click.stop="doThis"></a>
<!-- 提交事件不再重载页面 -->
<form v-on:submit.prevent="onSubmit"></form>
<!-- 修饰符可以串联 即阻止冒泡也阻止默认事件 -->
<a v-on:click.stop.prevent="doThat"></a>
<!-- 只当在 event.target 是当前元素自身时触发处理函数 -->
<!-- 即事件不是从内部元素触发的 -->
<div v-on:click.self="doThat">...</div>
使用修饰符时,顺序很重要;相应的代码会以同样的顺序产生。因此,用 v-on:click.prevent.self 会阻止所有的点击,而 v-on:click.self.prevent 只会阻止对元素自身的点击。
<div id="app">
<h1>{{num}}</h1>
<div v-on:click="add">
<button type="button" v-on:click.stop="change">change</button>
</div>
<a href="https://www.baidu.com" v-on:click.prevent="change">百度</a>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
msg: 'Hello Vue!',
num: 0
},
methods:{
add: function () {
this.num++;
},
change: function () {
}
}
})
</script>
按键修饰符
- 在做项目中有时会用到键盘事件,在监听键盘事件时,我们经常需要检查详细的按键。Vue 允许为
v-on
在监听键盘事件时添加按键修饰符
<div id="app">
预先定义了keycode 116(即F5)的别名为f5,因此在文字输入框中按下F5,会触发prompt方法
<input type="text" v-on:keydown.f5="prompt()">
</div>
<script>
Vue.config.keyCodes.f5 = 116;
let app = new Vue({
el: '#app',
methods: {
prompt: function() {
alert('我是 F5!');
}
}
});
</script>
小案例 - 计算器
<div id="app">
<h1>简单计算器</h1>
<div>
<span>数值A:</span>
<span>
<input type="text" v-model="a">
</span>
</div>
<div>
<span>数值B:</span>
<span>
<input type="text" v-model="b">
</span>
</div>
<div>
<button type="button" @click="calc">计算</button>
</div>
<div>
<span>计算结果: </span>
<span v-text="result"></span>
</div>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
a: '',
b: '',
result: ''
},
methods:{
calc: function () {
this.result = parseInt(this.a) + parseInt(this.b);
}
}
})
</script>
v-bind
- v-bind 指令被用来响应地更新 HTML 属性
- v-bind:href 可以缩写为 :href;
<div id="app">
<a v-bind:href="url">百度</a>
<!-- v-bind的简写形式-->
<a :href="url">百度</a>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
url: 'https://www.baidu.com'
}
})
</script>
使用v-bind实现双向绑定
<div id="app">
<h1>{{msg}}</h1>
<input type="text" v-bind:value="msg" v-on:input="handle">
<input type="text" v-bind:value="msg" v-on:input="msg = $event.target.value">
</div>
<script>
let app = new Vue({
el: '#app',
data: {
msg: 'Hello Vue!'
},
methods:{
handle: function (event) {
this.msg = event.target.value;
}
}
})
</script>
绑定对象
- 我们可以给v-bind:class 一个对象,以动态地切换class。
- 注意:v-bind:class指令可以与普通的class特性共存
<!-- 1、 v-bind 中支持绑定一个对象
如果绑定的是一个对象 则 键为 对应的类名 值 为对应data中的数据
-->
<!--
HTML最终渲染为 <ul class="box textColor textSize"></ul>
注意:
textColor,textSize 对应的渲染到页面上的CSS类名
isColor,isSize 对应vue data中的数据 如果为true 则对应的类名 渲染到页面上
当 isColor 和 isSize 变化时,class列表将相应的更新,
例如,将isSize改成false,
class列表将变为 <ul class="box textColor"></ul>
-->
<ul class="box" v-bind:class="{textColor:isColor, textSize:isSize}">
<li>学习Vue</li>
<li>学习Node</li>
<li>学习React</li>
</ul>
<div v-bind:style="{color:activeColor,fontSize:activeSize}">对象语法</div>
<sript>
var vm= new Vue({
el:'.box',
data:{
isColor:true,
isSize:true,
activeColor:"red",
activeSize:"25px",
}
})
</sript>
<style>
.box{
border:1px dashed #f0f;
}
.textColor{
color:#f00;
background-color:#eef;
}
.textSize{
font-size:30px;
font-weight:bold;
}
</style>
绑定class
2、 v-bind 中支持绑定一个数组 数组中classA和 classB 对应为data中的数据
这里的classA 对用data 中的 classA
这里的classB 对用data 中的 classB
<ul class="box" :class="[classA, classB]">
<li>学习Vue</li>
<li>学习Node</li>
<li>学习React</li>
</ul>
<script>
var vm= new Vue({
el:'.box',
data:{
classA:‘textColor‘,
classB:‘textSize‘
}
})
</script>
<style>
.box{
border:1px dashed #f0f;
}
.textColor{
color:#f00;
background-color:#eef;
}
.textSize{
font-size:30px;
font-weight:bold;
}
</style>
绑定对象和绑定数组 的区别
- 绑定对象的时候 对象的属性 即要渲染的类名 对象的属性值对应的是 data 中的数据
- 绑定数组的时候数组里面存的是data 中的数据
<div id="app">
<div :class="[errorClass,bgClass,{active:isActive}]">
<h1>test</h1>
</div>
<div :class="classes"></div>
<div :class="objClass"></div>
<div class="bg" :class="objClass"></div>
<button type="button" @click="change">切换</button>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
errorClass:'error',
bgClass:'bg',
isActive:false,
classes:['error','bg','active'],
objClass:{
active:true,
error:true
}
},
methods:{
change:function () {
this.isActive = !this.isActive;
}
}
})
</script>
<style scope>
.active{
width: 100px;
height: 100px;
border: 1px solid red;
}
.error{
color: red;
}
.bg{
background: deepskyblue;
}
</style>
绑定style
<div v-bind:style="styleObject">绑定样式对象</div>'
<!-- CSS 属性名可以用驼峰式 (camelCase) 或短横线分隔 (kebab-case,记得用单引号括起来) -->
<div v-bind:style="{ color: activeColor, fontSize: fontSize,background:'red' }">内联样式</div>
<!--组语法可以将多个样式对象应用到同一个元素 -->
<div v-bind:style="[styleObj1, styleObj2]"></div>
<script>
new Vue({
el: '#app',
data: {
styleObject: {
color: 'green',
fontSize: '30px',
background:'red'
},
activeColor: 'green',
fontSize: "30px"
},
styleObj1: {
color: 'red'
},
styleObj2: {
fontSize: '30px'
}
</script>
分支结构
v-if 使用场景
- 1- 多个元素 通过条件判断展示或者隐藏某个元素。或者多个元素
- 2- 进行两个视图之间的切换
<div id="app">
<!-- 判断是否加载,如果为真,就加载,否则不加载-->
<span v-if="flag">
如果flag为true则显示,false不显示!
</span>
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
flag:true
}
})
</script>
----------------------------------------------------------
<div v-if="type === 'A'">
A
</div>
<!-- v-else-if紧跟在v-if或v-else-if之后 表示v-if条件不成立时执行-->
<div v-else-if="type === 'B'">
B
</div>
<div v-else-if="type === 'C'">
C
</div>
<!-- v-else紧跟在v-if或v-else-if之后-->
<div v-else>
Not A/B/C
</div>
<script>
new Vue({
el: '#app',
data: {
type: 'C'
}
})
</script>
v-show 和 v-if的区别
- v-show本质就是标签display设置为none,控制隐藏
- v-show只编译一次,后面其实就是控制css,而v-if不停的销毁和创建,故v-show性能更好一点。
- v-if是动态的向DOM树内添加或者删除DOM元素
- v-if切换有一个局部编译/卸载的过程,切换过程中合适地销毁和重建内部的事件监听和子组件
<div id="app">
<div v-if="score >= 90">优秀</div>
<div v-else-if="score>=80 && score <90">良好</div>
<div v-else-if="score>=60 && score <80">一般</div>
<div v-else-if="score>=0 && score <60">比较差</div>
<div v-show="flag"><h1>测试v-show</h1></div>
<button type="button" @click="handle">显示</button>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
score: 80,
flag: false
},
methods:{
handle:function (event) {
if (this.flag){
event.target.innerHTML = '显示';
}else{
event.target.innerHTML = '隐藏';
}
this.flag = !this.flag;
}
}
})
</script>
循环结构
v-for
- 用于循环的数组里面的值可以是对象,也可以是普通元素
<ul id="example-1">
<!-- 循环结构-遍历数组
item 是我们自己定义的一个名字 代表数组里面的每一项
items对应的是 data中的数组-->
<li v-for="item in items">
{{ item.message }}
</li>
</ul>
<script>
new Vue({
el: '#example-1',
data: {
items: [
{ message: 'Foo' },
{ message: 'Bar' }
],
}
})
</script>
- 不推荐同时使用
v-if
和v-for
- 当
v-if
与v-for
一起使用时,v-for
具有比v-if
更高的优先级。
<!-- 循环结构-遍历对象
v 代表 对象的value
k 代表对象的 键
i 代表索引
--->
<div v-if='v==13' v-for='(v,k,i) in obj'>{{v + '---' + k + '---' + i}}</div>
<script>
new Vue({
el: '#example-1',
data: {
items: [
{ message: 'Foo' },
{ message: 'Bar' }
],
obj: {
uname: 'zhangsan',
age: 13,
gender: 'female'
}
}
})
</script>
key 的作用
- key来给每个节点做一个唯一标识
- key的作用主要是为了高效的更新虚拟DOM
<ul>
<li v-for="item in items" :key="item.id">...</li>
</ul>
<div id="app">
<ul>
<!-- <li v-for="item in fruits">{{item}}</li>-->
<!-- <br>-->
<li v-for="(item,index) in fruits">{{index + '----'+ item}}</li>
</ul>
<ul>
<!-- key来给每个节点做一个唯一标识 -->
<li v-for="(item,index) in myFruits" :key="item.id">
索引:{{index}}
<br>
英文:{{item.ename}}
<br>
中文:{{item.cname}}
</li>
</ul>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
fruits: ['apple', 'orange', 'banana'],
myFruits:[
{
id: 1,
ename:'apple',
cname:'苹果'
},
{
id: 2,
ename:'orange',
cname:'橙子'
},
{
id: 3,
ename:'banana',
cname:'香蕉'
}
]
}
})
</script>
小案例
<div id="app">
<div class="tab">
<ul>
<li @click="change(index)" :class='currentIndex==index?"active":""' :key="item.id" v-for="(item,index) in list">{{item.title}}</li>
</ul>
<div :class='currentIndex==index?"current":""' v-for="(item,index) in list">
<img :src="item.path" alt=""/>
</div>
</div>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
currentIndex:0,
list:[
{
id:1,
title:'apple',
path:'img/apple.png'
},
{
id:2,
title:'orange',
path:'img/orange.png'
},
{
id:3,
title:'lemon',
path:'img/lemon.png'
}
]
},
methods:{
change: function (index) {
this.currentIndex = index;
}
}
})
</script>
<style scope>
.tab ul {
overflow: hidden;
padding: 0;
margin: 0;
}
.tab ul li {
box-sizing: border-box;
padding: 0;
float: left;
width: 100px;
height: 45px;
line-height: 45px;
list-style: none;
text-align: center;
border-top: 1px solid blue;
border-right: 1px solid blue;
cursor
}
.tab ul li:first-child {
border-left: 1px solid blue;
}
.tab ul li.active {
background-color: orange;
}
.tab div {
width: 500px;
height: 300px;
display: none;
text-align: center;
font-size: 30px;
line-height: 300px;
border: 1px solid blue;
border-top: 0px;
}
.tab div.current {
display: block;
}
</style>