Vue3 学习笔记(五)Vue3 模板语法详解

news2024/10/28 2:29:22

在 Vue3 的世界里,模板语法是我们构建用户界面的基石。今天,让我们一起深入了解 Vue3 的模板语法,我将用通俗易懂的语言和实用的例子,带你掌握这项必备技能。


1、文本插值:最基础的开始


想在页面上显示数据?双大括号语法 {{ }} 就是你的好帮手!

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试)</title>

<script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/vue/3.2.26/vue.global.min.js"></script>

</head>
<body>

<div id="hello-vue" class="demo">
  {{ message }}
</div>

<script>
const HelloVueApp = {
  data() {
    return {
      message: '你好 Vue!!'
    }
  }
}

Vue.createApp(HelloVueApp).mount('#hello-vue')
</script>
</body>
</html>

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


2、插入 HTML:v-html 指令

双大括号会将数据解释为纯文本,而不是 HTML。

如果想插入 HTML,需要使用 v-html 指令.

 <p>使用双大括号的文本插值: {{ rawHtml }}</p>
 <p>使用 v-html 指令: <span v-html="rawHtml"></span></p>
</div>
 
<script>
const RenderHtmlApp = {
  data() {
    return {
      rawHtml: '<span style="color: red">这里会显示红色!</span>'
    }
  }
}
 
Vue.createApp(RenderHtmlApp).mount('#example1')
</script>


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


这里看到的 v-html attribute 被称为一个指令

指令由 v- 作为前缀,表明它们是一些由 Vue 提供的特殊 attribute,它们将为渲染的 DOM 应用特殊的响应式行为。这里我们做的事情简单来说就是:在当前组件实例上,将此元素的 innerHTML 与 rawHtml 属性保持同步。


3 、绑定属性:让元素活起来


双大括号不能在 HTML attributes 中使用。

想要响应式地绑定一个 attribute,应该使用 v-bind 指令。


(1)、常规 v-bind 指令
<div v-bind:id="dynamicId"></div>
<div v-bind:class="{'class1': use}">

测试案例:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试</title>
<script src="https://cdn.staticfile.net/vue/3.2.36/vue.global.min.js"></script>
<style>
.class1{
  background: #444;
  color: #eee;
}
</style>
</head>
<body>
<div id="app">
  <label for="r1">修改颜色</label><input type="checkbox" v-model="use" id="r1">
  <br><br>
  <div v-bind:class="{'class1': use}">
    v-bind:class 指令
  </div>
</div>

<script>
const app = {
  data() {
    return {
      use: false
    }
  }
}
 
Vue.createApp(app).mount('#app')
</script>
</body>
</html>

运行结果:

在这里插入图片描述


(2)、简写

v-bind 非常常用,简写语法:

<div :id="dynamicId"></div>

 <div :class="{'class1': use}">

开头为 : 的 attribute 可能和一般的 HTML attribute 看起来不太一样,但它的确是合法的 attribute 名称字符,并且所有支持 Vue 的浏览器都能正确解析它。此外,他们不会出现在最终渲染的 DOM 中。


(3)、布尔型 Attribute

对于布尔属性,常规值为 true 或 false,如果属性值为 null 或 undefined,则该属性不会显示出来。

<button v-bind:disabled="isButtonDisabled">按钮</button

(4)、类名和样式绑定
<!-- 类名绑定 -->
<div :class="{ active: isActive, 'text-danger': hasError }">
  动态类名
</div>

<!-- 样式绑定 -->
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }">
  动态样式
</div>

(5)、动态绑定多个值

如果有像这样的一个包含多个 attribute 的 JavaScript 对象:

const objectOfAttrs = {
  id: 'container',
  class: 'wrapper',
  style: 'background-color:green'
}

通过不带参数的 v-bind,可以将它们绑定到单个元素上:

<div v-bind="objectOfAttrs"></div>

使用案例:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 属性绑定示例</title>
<script src="https://cdn.staticfile.net/vue/3.2.36/vue.global.min.js"></script>
<style>
.wrapper {
  padding: 20px;
  margin: 10px;
  border-radius: 8px;
}
.active {
  border: 2px solid blue;
  color: white;
}
.large {
  font-size: 20px;
}
.centered {
  text-align: center;
}
</style>
</head>
<body>
<div id="app">
  <!-- 1. 基础绑定 -->
  <div v-bind="objectOfAttrs">
    基础属性绑定
  </div>

  <!-- 2. 动态修改属性 -->
  <div class="controls" style="margin: 20px 0;">
    <button @click="toggleTheme">切换主题</button>
    <button @click="toggleSize">切换大小</button>
    <button @click="addNewAttr">添加新属性</button>
  </div>

  <!-- 3. 组合绑定 -->
  <div 
    v-bind="objectOfAttrs"
    :class="additionalClasses"
  >
    组合属性绑定
  </div>

  <!-- 4. 显示当前属性值 -->
  <div style="margin-top: 20px;">
    <h3>当前属性值:</h3>
    <pre>{{ JSON.stringify(objectOfAttrs, null, 2) }}</pre>
  </div>

  <!-- 5. 自定义属性输入 -->
  <div style="margin-top: 20px;">
    <h3>添加新属性:</h3>
    <input v-model="newAttrKey" placeholder="属性名">
    <input v-model="newAttrValue" placeholder="属性值">
    <button @click="addCustomAttr">添加</button>
  </div>
</div>

<script>
const app = {
  data() {
    return {
      // 基础属性对象
      objectOfAttrs: {
        id: 'container',
        class: 'wrapper',
        style: 'background-color: #42b983',
        'data-custom': 'value'
      },
      // 是否使用暗色主题
      isDark: false,
      // 是否使用大号字体
      isLarge: false,
      // 新属性的输入值
      newAttrKey: '',
      newAttrValue: ''
    }
  },
  computed: {
    // 计算额外的类名
    additionalClasses() {
      return {
        'active': this.isDark,
        'large': this.isLarge,
        'centered': true
      }
    }
  },
  methods: {
    // 切换主题
    toggleTheme() {
      this.isDark = !this.isDark
      this.objectOfAttrs.style = this.isDark 
        ? 'background-color: #34495e; color: white'
        : 'background-color: #42b983'
    },
    // 切换大小
    toggleSize() {
      this.isLarge = !this.isLarge
    },
    // 添加新属性
    addNewAttr() {
      this.objectOfAttrs['data-timestamp'] = new Date().getTime()
    },
    // 添加自定义属性
    addCustomAttr() {
      if (this.newAttrKey && this.newAttrValue) {
        this.objectOfAttrs[this.newAttrKey] = this.newAttrValue
        this.newAttrKey = ''
        this.newAttrValue = ''
      }
    }
  }
}

Vue.createApp(app).mount('#app')
</script>
</body>
</html>

输出结果:

在这里插入图片描述


(6)、使用 JavaScript 表达式


Vue 实际上在所有的数据绑定中都支持完整的 JavaScript 表达式:

{{ number + 1 }}

{{ ok ? 'YES' : 'NO' }}

{{ message.split('').reverse().join('') }}

<div :id="`list-${id}`"></div>

这些表达式都会被作为 JavaScript ,以当前组件实例为作用域解析执行。

在 Vue 模板内,JavaScript 表达式可以被使用在如下场景上:

  • 在文本插值中 (双大括号)
  • 在任何 Vue 指令 (以 v- 开头的特殊 attribute) attribute 的值中

仅支持单一表达式


每个绑定仅支持单一表达式,也就是一段能够被求值的 JavaScript 代码。一个简单的判断方法是是否可以合法地写在 return 后面。

下面的例子无效

<!-- 这是一个语句,而非表达式 -->
{{ var a = 1 }}

<!-- 条件控制也不支持,请使用三元表达式 -->
{{ if (ok) { return message } }}

4、调用函数


可以在绑定的表达式中使用一个组件暴露的方法:

<time :title="toTitleDate(date)" :datetime="date">
  {{ formatDate(date) }}
</time>

使用案例:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 绑定表达式中的函数调用</title>
<script src="https://cdn.staticfile.net/vue/3.2.36/vue.global.min.js"></script>
<style>
.date-display {
  padding: 10px;
  margin: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  cursor: pointer;
}
.highlight {
  background-color: #e8f5e9;
}
.format-switch {
  margin: 10px 0;
}
time {
  display: inline-block;
  padding: 5px 10px;
}
time:hover {
  background-color: #f5f5f5;
}
</style>
</head>
<body>
<div id="app">
  <!-- 基础日期显示 -->
  <time 
    :title="toTitleDate(currentDate)" 
    :datetime="currentDate"
    class="date-display"
    :class="{ highlight: isHighlighted }"
    @click="toggleHighlight"
  >
    {{ formatDate(currentDate) }}
  </time>

  <!-- 格式切换 -->
  <div class="format-switch">
    <label>
      <input type="checkbox" v-model="useDetailedFormat">
      使用详细格式
    </label>
  </div>

  <!-- 多个日期展示 -->
  <div>
    <h3>日期列表:</h3>
    <time 
      v-for="date in dates" 
      :key="date"
      :title="toTitleDate(date)"
      :datetime="date"
      :style="getDateStyle(date)"
    >
      {{ formatDate(date) }}
    </time>
  </div>

  <!-- 日期计算 -->
  <div style="margin-top: 20px;">
    <button @click="addDays(1)">添加一天</button>
    <button @click="addDays(-1)">减少一天</button>
    <button @click="resetDate">重置日期</button>
  </div>

  <!-- 自定义格式输入 -->
  <div style="margin-top: 20px;">
    <input 
      v-model="customFormat" 
      placeholder="输入自定义格式"
      :title="getFormatExample()"
    >
  </div>
</div>

<script>
const app = {
  data() {
    return {
      currentDate: new Date().toISOString(),
      useDetailedFormat: false,
      isHighlighted: false,
      customFormat: 'YYYY-MM-DD',
      dates: [
        new Date().toISOString(),
        new Date(Date.now() - 86400000).toISOString(), // 昨天
        new Date(Date.now() + 86400000).toISOString()  // 明天
      ]
    }
  },
  methods: {
    // 格式化为标题日期
    toTitleDate(date) {
      const d = new Date(date)
      return d.toLocaleString('zh-CN', {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    },

    // 格式化显示日期
    formatDate(date) {
      const d = new Date(date)
      if (this.useDetailedFormat) {
        return this.toTitleDate(date)
      }
      return d.toLocaleDateString('zh-CN')
    },

    // 获取日期样式
    getDateStyle(date) {
      const d = new Date(date)
      const today = new Date()
      const isToday = d.toDateString() === today.toDateString()
      
      return {
        backgroundColor: isToday ? '#e3f2fd' : 'transparent',
        margin: '0 5px',
        borderRadius: '4px'
      }
    },

    // 切换高亮
    toggleHighlight() {
      this.isHighlighted = !this.isHighlighted
    },

    // 添加天数
    addDays(days) {
      const d = new Date(this.currentDate)
      d.setDate(d.getDate() + days)
      this.currentDate = d.toISOString()
    },

    // 重置日期
    resetDate() {
      this.currentDate = new Date().toISOString()
    },

    // 获取格式示例
    getFormatExample() {
      return `格式示例: ${this.formatDate(this.currentDate)}`
    }
  },
  watch: {
    // 监听自定义格式变化
    customFormat(newFormat) {
      console.log('Format changed:', newFormat)
    }
  }
}

Vue.createApp(app).mount('#app')
</script>
</body>
</html>

输出效果:

在这里插入图片描述


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2225112.html

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

相关文章

深度学习模型入门教程:从基础到应用

深度学习模型入门教程&#xff1a;从基础到应用 前言 在人工智能的浪潮中&#xff0c;深度学习作为一种强大的技术&#xff0c;正在各行各业中发挥着越来越重要的作用。从图像识别到自然语言处理&#xff0c;深度学习正在改变我们的生活和工作方式。本文将带您深入了解深度学…

OpenCV视觉分析之运动分析(3)背景减除类:BackgroundSubtractorKNN的一系列get函数的使用

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 BackgroundSubtractorKNN类有一系列的get函数&#xff0c;下面我们一一列举他们的名字和用法。 一系列函数 函数getDetectShadows() getDetec…

CSS伪元素以及伪类和CSS特性

伪元素&#xff1a;可以理解为假标签。 有2个伪元素 &#xff08;1&#xff09;::before &#xff08;2&#xff09;::after ::before <!DOCTYPE html> <html> <head><title></title><style type"text/css">body::before{con…

使用Python Pillow库生成九宫格图片

相信很多人看到过九宫格图片&#xff0c;一张完整的大图被分割成九张小图&#xff0c;在朋友圈和微博里一度成为流行。 相比完整的大图&#xff0c;九宫格图文增添了一丝趣味和精致&#xff0c;也显得更有创意。 制作九宫格图片的工具有很多&#xff0c;下文用Python的PIL库来…

Puppeteer 与浏览器版本兼容性:自动化测试的最佳实践

Puppeteer 支持的浏览器版本映射&#xff1a;从 v20.0.0 到 v23.6.0 自 Puppeteer v20.0.0 起&#xff0c;这个强大的自动化库开始支持与 Chrome 浏览器的无头模式和有头模式共享相同代码路径&#xff0c;为自动化测试带来了更多便利。从 v23.0.0 开始&#xff0c;Puppeteer 进…

vue3完整Demo(数据绑定,数据显示,数据修改,数据提交)

需要引入的的依赖&#xff1a;jquery&#xff08;用于异步请求&#xff09; 一、数据显示的前端页面 条件查询数据并显示&#xff0c;下拉框使用的model双向绑定 二、js代码&#xff08;list页面的数据请求&#xff09; 后端传来的时间数据需要转换可以使用new Intl.DateTim…

【NOIP提高组】加分二叉树

【NOIP提高组】加分二叉树 &#x1f490;The Begin&#x1f490;点点关注&#xff0c;收藏不迷路&#x1f490; 设一个n个节点的二叉树tree的中序遍历为&#xff08;l,2,3,…,n&#xff09;&#xff0c;其中数字1,2,3,…,n为节点编号。每个节点都有一个分数&#xff08;均为正整…

【Java并发编程】信号量Semaphore详解

一、简介 Semaphore&#xff08;信号量&#xff09;&#xff1a;是用来控制同时访问特定资源的线程数量&#xff0c;它通过协调各个线程&#xff0c;以保证合理的使用公共资源。 Semaphore 一般用于流量的控制&#xff0c;特别是公共资源有限的应用场景。例如数据库的连接&am…

redis详细教程(2.List教程)

List是一种可以存储多个有序字符串的数据类型&#xff0c;其中的元素按照顺序排列&#xff08;可以重复出现&#xff09;&#xff0c;可以通过数字索引来访问列表中的元素&#xff0c;索引可以从左到右或者从右到左。 Redis 列表可以通过两种方式实现&#xff1a;压缩列表&…

力扣283-- 移动零

开始做梦的地方 力扣283 &#xff1a; 给定一个数组 nums&#xff0c;编写一个函数将所有 0 移动到数组的末尾&#xff0c;同时保持非零元素的相对顺序。请注意 &#xff0c;必须在不复制数组的情况下原地对数组进行操作。 何解&#xff1f; 1&#xff0c;暴力枚举&#xff1a…

ElasticSearch备考 -- index rollover

一、题目 给索引my-index-000001&#xff0c;创建别名my-index&#xff0c;并设置rollover&#xff0c;满足以下三个条件的 The index was created 7 or more days ago.The index contains 5 or more documents.The index’s largest primary shard is 1GB or larger. 二、思考…

cmake命令使用

有关cmake的入门简介可参见 CMake入门教程_cmake静态test.c编译-CSDN博客 本文是进一步对cmake常用命令做进一步详述 配置项目 cmake_minimum_required 作用 配置cmake最低版本 用法 cmake_minimum_required(VERSION 3.0) project 作用&#xff1a;设置预设变量 PROJEC…

w002基于Springboot医护人员排班系统

&#x1f64a;作者简介&#xff1a;多年一线开发工作经验&#xff0c;原创团队&#xff0c;分享技术代码帮助学生学习&#xff0c;独立完成自己的网站项目。 代码可以查看文章末尾⬇️联系方式获取&#xff0c;记得注明来意哦~&#x1f339;赠送计算机毕业设计600个选题excel文…

Python数据分析基础

本文介绍了Python在数据分析中的应用&#xff0c;包括数据读取、清洗、处理和分析的基本操作。通过使用Pandas和Numpy库&#xff0c;我们可以高效地处理大量数据&#xff0c;并利用Matplotlib和Seaborn库进行数据可视化。 1. 引言 Python因其简洁的语法和强大的库支持&#x…

重学SpringBoot3-Spring WebFlux之Reactor事件感知 API

更多SpringBoot3内容请关注我的专栏&#xff1a;《SpringBoot3》 期待您的点赞&#x1f44d;收藏⭐评论✍ Spring WebFlux之Reactor事件感知 API 1. 什么是 doOnXxx 系列 API&#xff1f;2. doOnXxx API 的常用方法2.1 doOnNext()示例&#xff1a;输出&#xff1a; 2.2 doOnErr…

OCR经典神经网络(三)LayoutLM v2算法原理及其在发票数据集上的应用(NER及RE)

OCR经典神经网络(三)LayoutLM v2算法原理及其在发票数据集上的应用(NER及RE) LayoutLM系列模型是微软发布的、文档理解多模态基础模型领域最重要和有代表性的工作&#xff1a; LayoutLM v2&#xff1a;在一个单一的多模态框架中对文本&#xff08;text&#xff09;、布局&…

OpenAI GPT-o1实现方案记录与梳理

本篇文章用于记录从各处收集到的o1复现方案的推测以及介绍 目录 Journey Learning - 上海交通大学NYUMBZUAIGAIRCore IdeaKey QuestionsKey TechnologiesTrainingInference A Tutorial on LLM Reasoning: Relevant methods behind ChatGPT o1 - UCL汪军教授Core Idea先导自回归…

anaconda 创建环境失败 解决指南

anaconda 创建环境失败 解决指南 一、问题描述 我在宿舍有一台电脑。由于我经常泡在实验室&#xff0c;所以那台电脑不是经常用&#xff0c;基本吃灰。昨天晚上突然有在那台电脑上使用Camel-AI部署多智能体协同需求&#xff0c;便戳开了电脑&#xff0c;问题也随之而来。 当…

开源实时数仓的构建

设计计思路 基本思路 开源数据平台的设计思路是通过 Flink SQL Batch、StartRocks SQL 、StartRocks物化视图 的能力实现一个离线任务的开发&#xff1b;使用 DolphinScheduler 进行离线工作流编排和调度&#xff1b;通过 Flink CDC 和 Flink SQL 实现流处理能力&#xff0c;进…

【自然语言处理】BERT模型

BERT&#xff1a;Bidirectional Encoder Representations from Transformers BERT 是 Google 于 2018 年提出的 自然语言处理&#xff08;NLP&#xff09;模型&#xff0c;它基于 Transformer 架构的 Encoder 部分。BERT 的出现极大提升了 NLP 任务的性能&#xff0c;如问答系…