Vue超详细知识点学习(第二节)

好的,今天我们来学习一下Vue指令。

1,v-bind指令

作用:动态的设置html的标签属性
语法:v-bind:titile="msg"
简写::title="msg"
注意点:v-bind访问的值,必须在data中存在

2,v-model指令

作用:在变淡元素上创建双向数据绑定
双向数据绑定:将DOM与Vue实例的data数据绑定到一起,彼此之间相互影响
数据的改变会引起DOM的改变
DOM的改变也会引起数据的改变
原理:数据劫持,object.defineproperty中的getset方法
注意:object.defineproperty方法是ES5中提供的,IE8浏览器不支持这个方法,因此,Vue不支持IE8及以下浏览器

3,Vue双向绑定的极简实现

<!-- 示例 -->
<input type="text" id="txt" />
<span id="msgBox"></span>

<script>
const txt = document.getElementById('txt')
const msgBox = document.getElementById('msgBox')
const obj = {
    
    }

// 给对象obj添加msg属性,并设置setter访问器
Object.defineProperty(obj, 'msg', {
    
    
  // 设置 obj.msg 执行的操作
  set: function (curVal) {
    
    
    txt.value = curVal
    msgBox.innerText = curVal
  }
})

// 监听文本框的改变
txt.addEventListener('input', function (event) {
    
    
  obj.msg = this.value
})
</script>

3,v-on指令

作用:绑定事件
语法:v-onclick="say"v-onclick="say('参数',$event)"
简写 :@click="say"
说明:绑定的事件从methods中获取

<button @click="Function($event)">按钮</button> //简写 获取事件对象

4,事件修饰符

.stop阻止冒泡,调用event.stopPropagation()
.prevent阻止默认行为,调用event.preventDefault()
.capture添加事件侦听器时使用事件捕获模式
self只当事件在该元素本身(比如不是子元素)触发时,才会触发的事件。
once事件只触发一次

5,按键修饰符
在监听键盘事件时,我们经常需要检查常见的键值,Vue允许为v-on在监听键盘事件时添加键盘修饰符:

.enter
.tab
.delete (捕获“删除”和“退格”键)
.esc
.space
.up
.down
.left
.right

6,v-text指令

解释:更新元素的文字内容。如果需要更新部分的内容,需要使用{ {}}插值

<span v-text="msg"></span>
<!-- 和下面的一样 -->
<span>{
    
    {
    
    msg}}</span>

7,v-for

作用:基于源数据多次渲染元素模块

<!-- 1 基础用法 -->
<div v-for="item in items">
  {
    
    {
    
     item.text }}
</div>

<!-- item 为当前项,index 为索引 -->
<p v-for="(item, index) in list">{
    
    {
    
    item}} -- {
    
    {
    
    index}}</p>
<!-- item 为值,key 为键,index 为索引 -->
<p v-for="(item, key, index) in obj">{
    
    {
    
    item}} -- {
    
    {
    
    key}}</p>
<p v-for="item in 10">{
    
    {
    
    item}}</p>

8,key属性

推荐:使用v-for的时候提供key属性,能够提升列表渲染的性能!

<div v-for="item in items" :key="item.id">
  <!-- 内容 -->
</div>

9,v-if和v-show

v-if:根据表达式的值的真假条件,销毁或重建元素。
v-show:根据表达式的真假值,切换元素的display css属性、

10,样式处理-class和style

使用方式:v-bind:class="flag":calss="flag" 表达式的类型:字符串,数组,对象

语法:

<!-- 重点 -->
<div v-bind:class="{ active: true }"></div> ===>
<div class="active"></div>

<!-- 2 -->
<div :class="['active', 'text-danger']"></div> ===>
<div class="active text-danger"></div>

<!-- 3 -->
<div v-bind:class="[{ active: true }, errorClass]"></div> ===>
<div class="active text-danger"></div>


--- style ---
<!-- 1 -->
<div v-bind:style="{ color: activeColor, 'font-size': fontSize + 'px' }"></div>
<!-- 2 将多个 样式对象 应用到一个元素上-->
<!-- baseStyles 和 overridingStyles 都是对象 -->
<div v-bind:style="[baseStyles, overridingStyles]"></div>

11,提升性能:v-pre

说明:跳过这个元素和它的元素的编译过程。可以用来显示原始{ {}}标签,跳过大量没用的指令节点加快编译。

<span v-once>This will never change: {
    
    {
    
    msg}}</span>

好了,vue的指令常用的就这些了。

猜你喜欢

转载自blog.csdn.net/weixin_46533797/article/details/109841219