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

news2024/9/21 19:08:59

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.coloradmin.cn/o/1061120.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Chrome之解决DevTools: Failed to load data:No resource with given identifier found

问题 使用DevTools抓包时候, 有些跨域请求无法在加载出来, 提示 Failed to load data:No resource with given identifier found 解决办法 换其他浏览器 下断点 打开DevTools, 选择源代码/来源/Sources,找到事件监听器断点/Event Listener Breakpoints, 找到加载/Load下面…

C++树详解

树 树的定义 树&#xff08;Tree&#xff09;是n&#xff08;n≥0&#xff09;个结点的有限集。n0时称为空树。在任意一颗非空树中&#xff1a;①有且仅有一个特定的称为根&#xff08;Root&#xff09;的结点&#xff1b;②当n>1时&#xff0c;其余结点可分为m&#xff08…

十天学完基础数据结构-第七天(图(Graph))

图的基本概念 图是一种数据结构&#xff0c;用于表示对象之间的关系。它由两个基本组件构成&#xff1a; 顶点&#xff08;Vertex&#xff09;&#xff1a;也被称为节点&#xff0c;代表图中的对象或实体。 边&#xff08;Edge&#xff09;&#xff1a;连接两个顶点的线&…

【setxattr+userfaultfd】SECCON2020-kstack

这个题主要还是练习 userfaultfd 的利用。说实话&#xff0c;userfaultfd 的利用还是挺多的&#xff0c;虽然在新的内核版本已经做了相关保护。 老规矩&#xff0c;看下启动脚本 #!/bin/sh qemu-system-x86_64 \-m 128M \-kernel ./bzImage \-initrd ./rootfs.cpio \-append …

第三章、运输层

文章目录 3.1 概述和运输层服务3.1.1 运输层和网络层的关系3.1.2 因特网运输层概述 3.2 多路复用与多路分解3.3 无连接运输&#xff1a;UDP3.4 可靠数据传输原理3.4.1构造可靠数据传输协议rdt1.0rdt2.xrdt3.0 3.4.2 流水线可靠数据传输协议3.4.3 回退N步3.4.4选择重传 3.5 面向…

x64内核实验1-调试环境配置

x64内核实验1-调试环境配置 这是一套x64内核实验的课程&#xff0c;我之前学习32位内核的时候就是在网上找的各种教程当学完32位很久之后发现在网上的64位内核相关的完整教程真的很少&#xff0c;所以就想着不如自己写一点方便对内核有兴趣的人能更好的入门&#xff0c;首先声…

哈希原理和解决哈希冲突方法

第一 哈希介绍 哈希和红黑树是我早期就听过的名词&#xff0c;却一直没见到真面目&#xff0c;实现哈希后才发现原来我早就使用过了哈希。看下面例题。 用map和set都可以轻松解决&#xff0c;但是在我写这题时我还不会用map和set&#xff0c;我用了另一种方法。看下面代码。先定…

【Java】微服务——Nacos配置管理(统一配置管理热更新配置共享Nacos集群搭建)

目录 1.统一配置管理1.1.在nacos中添加配置文件1.2.从微服务拉取配置1.3总结 2.配置热更新2.1.方式一2.2.方式二2.3总结 3.配置共享1&#xff09;添加一个环境共享配置2&#xff09;在user-service中读取共享配置3&#xff09;运行两个UserApplication&#xff0c;使用不同的pr…

Office Tool Plus下载与神龙版官网下载

文章目录 一、Office Tool Plus下载二、神龙下载 Office Tool Plus简称OTP&#xff0c;是一款专业的Office官方镜像下载器&#xff0c;可以下载安装Word、Excel、Visio等。神龙用于快速激活使用。 注意&#xff1a;Win7系统必须要SP1或更高版本才能使用&#xff0c;Office Tool…

intel 一些偏门汇编指令总结

intel 汇编手册下载链接&#xff1a;https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html LDS指令&#xff1a; 手册中可以找到 位于 3-588 根据手册内容猜测&#xff1a;lds r16 m16:16 的作用&#xff0c;是把位于 [m16:16] 内存地址的数…

JMeter的详细使用及相关问题

一、中文乱码问题 如果出现乱码&#xff0c;需要修改编码集&#xff0c;&#xff08;版本问题有的不需要修改&#xff0c;就不用管&#xff09; 修改后保存重启就好了。 JMeter5.5版本的按照如下修改&#xff1a; 二、JMeter的启动 ①建议直接用ApacheJMeter.jar双击启动…

Zabbix4自定义脚本监控MySQL数据库

一、MySQL数据库配置 1.1 创建Mysql数据库用户 [rootmysql ~]# mysql -uroot -p create user zabbix127.0.0.1 identified by 123456; flush privileges; 1.2 添加用户密码到mysql client的配置文件中 [rootmysql ~]# vim /etc/my.cnf.d/client.cnf [client] host127.0.0.1 u…

CSDN博主粉丝数突破10万:坚持分享的力量与收获

今天&#xff0c;我在CSDN上看到了一位好友的统计数据&#xff0c;他统计了CSDN上所有粉丝数量排名靠前的博主的排名。虽然这个统计可能存在一些误差&#xff0c;但大体上应该是准确的。我惊讶地发现&#xff0c;截止到2023年10月4日&#xff0c;我的粉丝数量已经达到了101,376…

QScrollArea样式

QScrollBar垂直滚动条分为sub-line、add-line、add-page、sub-page、up-arrow、down-arrow和handle几个部分。 QScrollBar水平滚动条分为sub-line、add-line、add-page、sub-page、left-arrow、right-arrow和handle几个部分。 部件如下图所示&#xff1a; /* 整个滚动…

Pikachu靶场——文件包含漏洞(File Inclusion)

文章目录 1. File Inclusion1.2 File Inclusion(local)1.2.1 源代码分析1.2.2 漏洞防御 1.3 File Inclusion(remote)1.3.1 源代码分析1.3.2 漏洞防御 1.4 文件包含漏洞防御 1. File Inclusion 还可以参考我的另一篇文章&#xff1a;文件包含漏洞及漏洞复现。 File Inclusion(…

商业智能系统的主要功能包括数据仓库、数据ETL、数据统计输出、分析功能

ETL服务内容包含&#xff1a; 数据迁移数据合并数据同步数据交换数据联邦数据仓库

plt 画图不显示label

没写 plt.legend() 这个 ! # 效果模拟-------------- import matplotlib.pyplot as plt import matplotlib as mpl # matplotlib其实是不支持显示中文的 显示中文需要一行代码设置字体 mpl.rcParams[font.family] = STKAITI # STKAITI——字体 plt.rcParams[axes.unicode_m…

亲,您的假期余额已经严重不足了......

引言 大家好&#xff0c;我是亿元程序员&#xff0c;一位有着8年游戏行业经验的主程。 转眼八天长假已经接近尾声了&#xff0c;今天来总结一下大家的假期&#xff0c;聊一聊假期关于学习的看法&#xff0c;并预估一下大家节后大家上班时的样子。 1.放假前一天 即将迎来八天…

侯捷 C++ STL标准库和泛型编程 —— 9 STL周围

最后一篇&#xff0c;完结辽&#xff01;&#x1f60b; 9 STL周围 9.1 万用Hash Function Hash Function的常规写法&#xff1a;其中 hash_val 就是万用Hash Function class CustumerHash { public:size_t operator()(const Customer& c) const{ return hash_val(c.fna…

x64内核实验2-段机制的变化

x64内核实验2-段机制的变化 ia-32e模式简介 x86下的段描述符结构图如下 在x86环境下段描述符主要分为3个部分的内容&#xff1a;base、limit、attribute&#xff0c;而到了64位环境下段的限制越来越少&#xff0c;主要体现在base和limit已经不再使用而是直接置空&#xff0…