VUE3照本宣科——内置指令与自定义指令及插槽

news/2024/7/10 1:53:31 标签: Vue, 前端, 开发语言

VUE3照本宣科——内置指令与自定义指令及插槽

  • 前言
  • 一、内置指令
    • 1.v-text
    • 2.v-html
    • 3.v-show
    • 4.v-if
    • 5.v-else
    • 6.v-else-if
    • 7.v-for
    • 8.v-on
    • 9.v-bind
    • 10.v-model
    • 11.v-slot
    • 12.v-pre
    • 13.v-once
    • 14.v-memo
    • 15.v-cloak
  • 二、自定义指令
  • 三、插槽
    • 1.v-slot
    • 2.useSlots
    • 3.defineSlots()


前言

👨‍💻👨‍🌾📝记录学习成果,以便温故而知新

“VUE3照本宣科”是指照着中文官网和菜鸟教程这两个“本”来学习一下VUE3。以前也学过VUE2,当时只再gitee留下一些代码,却没有记录学习的心得体会,有时也免不了会追忆一下。

以后出现“中文官网”不做特殊说明就是指:https://cn.vuejs.org/;菜鸟教程就是指:https://www.runoob.com/vue3/vue3-tutorial.html


一、内置指令

之所把内置指令一一罗列,主要是因为几个指令的缩写老是记不住,所以这里加深一下印象,做个备忘。同时也是作为基础知识的一部分。

1.v-text

更新元素的文本内容。

演示代码:

const msg = ref('Hello Tom')
<div>
	 <span v-text="msg"></span>
</div>

<div>
   <!-- 等同于 -->
   <span>{{ msg }}</span>
</div>

运行效果:
在这里插入图片描述如果是用双大括号输出,可以接受表达式。

2.v-html

更新元素的 innerHTML。
v-html 的内容直接作为普通 HTML 插入—— Vue 模板语法是不会被解析的。

演示代码:

const html = ref('<h1>{{ msg }}</h1>')
<div v-html="html"></div>

运行效果:
在这里插入图片描述

3.v-show

基于表达式值的真假性,来改变元素的可见性。

演示代码:

const ok = ref(true)
<div v-show="ok">v-show</div>
<div><button @click="ok=!ok">{{ ok ? '隐藏' : '显示' }}</button></div>

运行效果:
在这里插入图片描述如果单击“隐藏”按钮,则隐藏v-show指令所在的div,如图:
在这里插入图片描述v-show指令只是隐藏div,并不删除div,这点与v-if不一样。下图能够说明v-show指令所在的div被设置了style=“display: none;”
在这里插入图片描述

4.v-if

基于表达式值的真假性,来条件性地渲染元素或者模板片段。
当同时使用时,v-if 比 v-for 优先级更高。我们并不推荐在一元素上同时使用这两个指令

5.v-else

表示 v-if 或 v-if / v-else-if 链式调用的“else 块”。

6.v-else-if

表示 v-if 的“else if 块”。可以进行链式调用。

v-if 、v-else 与v-else-if 演示代码:

<div v-if="Math.random() > 0.5">
 Now you see me
</div>
<div v-else>
  Now you don't
</div>

<div v-if="type === 'A'">
  A
</div>
<div v-else-if="type === 'B'">
  B
</div>
<div v-else-if="type === 'C'">
  C
</div>
<div v-else>
  Not A/B/C
</div>

运行效果:
在这里插入图片描述

7.v-for

基于原始数据多次渲染元素或模板块。
期望的绑定值类型:Array | Object | number | string | Iterable

演示代码:

const items = reactive([1, 2, 3, 4, 5])

const user = ref({
  'name': 'Tom',
  'age': 16
})
<div v-for="(item, index) in items" :key="index">{{ index }} - {{ item }}</div>
<div v-for="(value, key) in user" :key="key">{{ key }} - {{ value }}</div>
<div v-for="(value, name, index) in user" :key="index">{{ index }} - {{ name }} - {{ value }}</div>

运行效果:
在这里插入图片描述
这里由于eslint的原因,以上代码的没有报错,还有其它的写法,但是报错了,所以就没有展示。

8.v-on

给元素绑定事件监听器。
缩写:@
参数:event (使用对象语法则为可选项)

修饰符

  • .stop - 调用 event.stopPropagation()。
  • .prevent - 调用 event.preventDefault()。
  • .capture - 在捕获模式添加事件监听器。
  • .self - 只有事件从元素本身发出才触发处理函数。
  • .{keyAlias} - 只在某些按键下触发处理函数。
  • .once - 最多触发一次处理函数。
  • .left - 只在鼠标左键事件触发处理函数。
  • .right - 只在鼠标右键事件触发处理函数。
  • .middle - 只在鼠标中键事件触发处理函数。
  • .passive - 通过 { passive: true } 附加一个 DOM 事件。

演示代码:

const doThis = (e) => console.log(e)

const doThat = (e) => console.log(e)

const onEnter = (e) => console.log(e)

const event = ref('click')
<!-- 方法处理函数 -->
<div><button v-on:click="doThis">v-on:click</button></div>

<!-- 动态事件 -->
<div><button v-on:[event]="doThis">v-on:[event]</button></div>

<!-- 内联声明 -->
<div><button v-on:click="doThat('hello', $event)">v-on:click</button></div>

<!-- 缩写 -->
<div><button @click="doThis">@click</button></div>

<!-- 使用缩写的动态事件 -->
<div><button @[event]="doThis">@[event]</button></div>

<!-- 停止传播 -->
<div><button @click.stop="doThis">@click.stop</button></div>

<!-- 阻止默认事件 -->
<div><button @click.prevent="doThis">@click.prevent</button></div>

<!-- 不带表达式地阻止默认事件 -->
<div><form @submit.prevent>@submit.prevent</form></div>

<!-- 链式调用修饰符 -->
<div><button @click.stop.prevent="doThis">@click.stop.prevent</button></div>

<!-- 按键用于 keyAlias 修饰符-->
<div><input @keyup.enter="onEnter" /></div>

<!-- 点击事件将最多触发一次 -->
<div><button v-on:click.once="doThis">v-on:click.once</button></div>

<!-- 对象语法 -->
<div><button v-on="{ mousedown: doThis, mouseup: doThat }">v-on=</button></div>

运行效果:
在这里插入图片描述挨个点击按钮或者输入框里输入回车,终端输出如图:
在这里插入图片描述除了form没有效果以外,其它都有输出。

9.v-bind

动态的绑定一个或多个 attribute,也可以是组件的 prop。
缩写:: 或者 . (当使用 .prop 修饰符)

修饰符

  • .camel - 将短横线命名的 attribute 转变为驼峰式命名。
  • .prop - 强制绑定为 DOM property。
  • .attr - 强制绑定为 DOM attribute。

演示代码:

const imageSrc = ref('../../public/nutcracker.jpg')

const fileName = ref('nutcracker.jpg')

const key = ref('style')
const value = ref('color:blue;text-align:center')

const isRed = ref(true)

const classA = ref('classA')
const classB = ref('classB')
// eslint-disable-next-line no-unused-vars
const classC = ref('classC')

const isB = ref(true)
const isC = ref(true)

const size = ref(20)

const styleObjectA = reactive({ color: 'red' })
const styleObjectB = reactive({ fontSize: '20px' })

const someProp = ref('someProp')
<div>
<!-- 绑定 attribute -->
<img v-bind:src="imageSrc" style="width:100px;height:100px;" />
</div>

<div>
<!-- 动态 attribute 名 -->
<button v-bind:[key]="value">v-bind:[key]="value"</button>
</div>

<div>
<!-- 缩写 -->
<img :src="imageSrc" style="width:100px;height:100px;"/>
</div>

<div>
<!-- 缩写形式的动态 attribute 名 -->
<button :[key]="value">:[key]="value"</button>
</div>

<div>
<!-- 内联字符串拼接 -->
<img :src="'../../public/' + fileName" style="width:100px;height:100px;" />
</div>

<!-- class 绑定 -->
<div :class="{ red:isRed }">:class="{ red:isRed }"</div>
<div :class="[classA, classB]">:class="[classA, classB]"</div>
<div :class="[classA, { classB:isB, classC:isC }]">:class="[classA, { classB: isB, classC: isC }]"</div>

<!-- style 绑定 -->
<div :style="{ fontSize: size + 'px' }">:style="{ fontSize: size + 'px' }"</div>
<div :style="[styleObjectA, styleObjectB]">:style="[styleObjectA, styleObjectB]"</div>

<!-- 绑定对象形式的 attribute -->
<div v-bind="{ id: someProp, 'style': styleObjectB }">v-bind="{ id: someProp, 'style': styleObjectB }"</div>
.red {
  color: red;
}

.classA {
  color: yellow;
}

.classB {
  font-size: 20px;
}

.classC {
  text-decoration: underline;
}

运行效果:
在这里插入图片描述截图中两个按钮绑定了样式,所以文字成了蓝色。

10.v-model

在表单输入元素或组件上创建双向绑定。

演示代码:

const color = ref('红')
const colors = ref([])
<div><input type="text" v-model="color" /></div>
<div>
  <input type="radio" id="red1" v-model="color" value=""/><label for="red1"></label>
  <input type="radio" id="yellow1" v-model="color" value=""/><label for="yellow1"></label>
  <input type="radio" id="blue1" v-model="color" value=""/><label for="blue1"></label>
</div>
<div>
  <select v-model="color">
    <option value=""></option>
    <option value=""></option>
    <option value=""></option>
  </select>
</div>
<br>
<div><textarea v-model="colors"></textarea></div>
<div>
  <input type="checkbox" id="red2" v-model="colors" value=""/><label for="red2"></label>
  <input type="checkbox" id="yellow2" v-model="colors" value=""/><label for="yellow2"></label>
  <input type="checkbox" id="blue2" v-model="colors" value=""/><label for="blue2"></label>
</div>

运行效果:
在这里插入图片描述
代码实现了文本框、单选按钮、下拉框、文本域与复选框的双向绑定。

11.v-slot

用于声明具名插槽或是期望接收 props 的作用域插槽。
缩写:#

这个指令在后面介绍。

12.v-pre

跳过该元素及其所有子元素的编译。

演示代码:

<span v-pre>{{ this will not be compiled }}</span>

运行效果:
在这里插入图片描述

13.v-once

仅渲染元素和组件一次,并跳过之后的更新。

演示代码:

const onceMsg = ref('Hello Jerry')
<div><span v-once>This will never change: {{ onceMsg }}</span></div>
<div><span>This will change: {{ onceMsg }}</span></div>
<div><input v-model="onceMsg" /></div>

运行效果:
在这里插入图片描述加了v-once指令的div果然只渲染了一次,修改文本框并没有更新。

14.v-memo

缓存一个模板的子树。在元素和组件上都可以使用。

中文文档中说:

v-memo 仅用于性能至上场景中的微小优化,应该很少需要。

所以就不介绍了。

15.v-cloak

用于隐藏尚未完成编译的 DOM 模板。

该指令只在没有构建步骤的环境下需要使用。

演示代码:

<div v-cloak>
  {{ message }}
</div>

这个代码只在特定场景或特定情况下才能看到效果。

二、自定义指令

本地的自定义指令在 <script setup> 中不需要显式注册,但他们必须遵循 vNameOfDirective 这样的命名规范。

演示代码:

const vMyDirective = {
  beforeMount: (el) => {
    // 在元素上做些操作
    el.style.color = '#FF0000'
    console.log(el)
  }
}
<h1 v-my-directive>This is a Heading</h1>

运行效果如图:
在这里插入图片描述
自定义指令已经起到了作用,因为颜色已经变成了红色。

三、插槽

1.v-slot

定义带插槽子组件TestChild3.vue,代码如下:

<template>
  <div>
    <div><slot>default</slot></div>
    <div><slot name="header">header</slot></div>
    <div><slot name="footer">footer</slot></div>
  </div>
</template>

引用子组件代码:

import Child from '/src/components/TestChild3.vue'
<Child></Child>
<br>
<Child>默认</Child>
<br>
<Child>
  <template v-slot:header>引用header</template>
</Child>
<br>
<Child>
  <template v-slot:default>引用default</template>
  <template v-slot:header>引用header</template>
  <template v-slot:footer>引用footer</template>
</Child>

运行结果:
在这里插入图片描述

2.useSlots

在子组件TestChild3.vue添加如下代码:

<script setup>
import { useSlots, onMounted } from 'vue'

const slots = useSlots()//能获取到this的情况下,也可以使用this.$slots

onMounted(() => {
  console.log(slots)
})
</script>

终端输出如图:
在这里插入图片描述

3.defineSlots()

中文文档中说:

这个宏可以用于为 IDE 提供插槽名称和 props 类型检查的类型提示。
它还返回 slots 对象,该对象等同于在 setup 上下文中暴露或由 useSlots() 返回的 slots 对象。

目前发现貌似不是lang="ts"是用不起来的。要是以后发现不是lang="ts"也能用再来介绍。


http://www.niftyadmin.cn/n/5067223.html

相关文章

数据分析:数据分析篇

文章目录 第一章 科学计算库Numpy1.1 认识Ndarray1.2 Ndarray的属性1.3 Numpy中的数据类型1.4 Numpy数组1.4.1 Numpy数组的创建1.4.2 Numpy数组的基本索引和切片1.4.3 Numpy布尔索引1.4.4 数组运算和广播机制1.4.5 Numpy数组的赋值和Copy复制1.4.6 Numpy数组的形状变换1.4.7 Nu…

JS短信倒计时案例

<!DOCTYPE html> <html lang"en"> <!-- 案例分析&#xff1a; 1. 按钮点击之后&#xff0c;会变成禁用状态(disabled为ture) 2. 同时按钮里面的内容会变化,button里面的内容通过innerHTML修改 3. 按钮中的秒数发生变化&#xff0c;因此需要用到定时器…

python写一个开机启动的选项

创建一个Python脚本&#xff0c;以便用户可以选择在开机时启动它&#xff0c;可以使用pyautogui库来创建一个简单的交互式界面&#xff0c;其中用户可以选择是否将程序添加到开机启动项中 import pyautogui import osdef add_to_startup():# 提示用户选择是否要在开机时启动程序…

Llama2-Chinese项目:8-TRL资料整理

TRL&#xff08;Transformer Reinforcement Learning&#xff09;是一个使用强化学习来训练Transformer语言模型和Stable Diffusion模型的Python类库工具集&#xff0c;听上去很抽象&#xff0c;但如果说主要是做SFT&#xff08;Supervised Fine-tuning&#xff09;、RM&#x…

Apollo Planning2.0决策规划算法代码详细解析 (2): vscode gdb单步调试环境搭建

前言: apollo planning2.0 在新版本中在降低学习和二次开发成本上进行了一些重要的优化,重要的优化有接口优化、task插件化、配置参数改造等。 GNU symbolic debugger,简称「GDB 调试器」,是 Linux 平台下最常用的一款程序调试器。GDB 编译器通常以 gdb 命令的形式在终端…

优思学院|六西格玛将烹饪和美味提升至极致

最近&#xff0c;我们曾提到一个美国男子如何利用六西格玛来控制糖尿病。这表明六西格玛逐渐被认为是一个不仅可以在工作场所之外使用&#xff0c;尤其不仅限于制造业的系统。 六西格玛的核心理念是改进过程的质量&#xff0c;从而改善最终结果。如果你做了晚餐或尝试了一道新…

动态规划五步曲

一、什么是动态规划五步曲 确定dp数组&#xff08;dp table&#xff09;以及下标的含义 确定递推公式 dp数组如何初始化 确定遍历顺序 举例推导dp数组 二、 个人赏析 这是我从某网站上看到的关于动态规划的教学系列。作为应试来说&#xff0c;这个 提纲确实不错&#xff0c;…

【1++的刷题系列】之双指针

&#x1f44d;作者主页&#xff1a;进击的1 &#x1f929; 专栏链接&#xff1a;【1的刷题系列】 文章目录 一&#xff0c;什么是双指针二&#xff0c;相关例题例一例二例三例四例五 一&#xff0c;什么是双指针 常见的双指针有两种形式&#xff1a;一种是对撞指针&#xff08…