温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue3中的模板语法和vue指令怎么使用

发布时间:2022-08-08 15:39:05 来源:亿速云 阅读:149 作者:iii 栏目:开发技术

本文小编为大家详细介绍“Vue3中的模板语法和vue指令怎么使用”,内容详细,步骤清晰,细节处理妥当,希望这篇“Vue3中的模板语法和vue指令怎么使用”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

1 模板插值语法

  • 在script 声明一个变量可以直接在template 使用用法为{{变量名称}}

  • 模板语法是可以编写条件运算的

  • 运算也是支持的

  • 操作API 也是支持的

<template>
  {{ message }}
    {{ message2==0 ? '我是老大' : '我笑的' }}
    {{ message2 + 1 }}
    {{ message.split('').map(v => `4546$v`) }}
</template>

<script setup lang="ts">
const message = "我是唐少"
const message2:number = 1
</script>
<style>
</style>

2 指令

  • v- 开头都是vue 的指令

  • v-text 用来显示文本

  • v-html 用来展示富文本

  • v-if 用来控制元素的显示隐藏(切换真假DOM)

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

  • v-else v-if条件收尾语句

  • v-show 用来控制元素的显示隐藏(display none block Css切换)

  • v-on 简写@ 用来给元素添加事件

  • v-bind 简写: 用来绑定元素的属性Attr

  • v-model 双向绑定

  • v-for 用来遍历元素

v-on修饰符

冒泡案例:

<template>
  <div @click="parent">parent
    <div @click.stop="child">child</div>
  </div>
</template>
  
<script setup lang="ts">
const child = () => {
  console.log('child');
 // 点击后不会答应parent,因为被阻止了
}
const parent = () => {
  console.log('parent');
}
  
</script>

阻止表单提交案例:

<template>
  <form action="/">
    <button @click.prevent="submit" type="submit">submit</button>
  </form>
</template>
<script setup lang="ts">
const submit = () => {
  console.log('child');
  
}
</script>
<style>
</style>

v-bind 绑定class 案例 1:

<template>
  <div :class="[flag ? 'active' : 'other', 'h']">456789</div>
</template>
<script setup lang="ts">
const flag: boolean = false;// 改成true后切换不同的效果
</script>
  
<style>
.active {
  color: red;
}
.other {
  color: blue;
}
.h {
  height: 300px;
  border: 1px solid #ccc;
}
</style>

v-bind 绑定class 案例 2:

<template>
  <div :class="flag">{{flag}}</div>
</template>
 // 直接绑定cls
<script setup lang="ts">
type Cls = {
  other: boolean,
  h: boolean
}
const flag: Cls = {
  other: false,
  h: true
};
</script>
<style>
.active {
  color: red;
}
.other {
  color: blue;
}
.h {
  height: 300px;
  border: 1px solid #ccc;
}
</style>

v-bind 绑定style案例:

<template>
  <div :>绑定style</div>
</template>
<script setup lang="ts">
type Style = {
  height: string,
  color: string
}
const style: Style = {
  height: "300px",
  color: "blue"
}
</script>
<style>
</style>

v-model 案例:

<template>
  <input v-model="message" type="text" />
  <div>{{ message }}</div>
</template>
<script setup lang="ts">
import { ref } from 'vue' // 实时监听
const message = ref("message")
</script>
  
<style>
.active {
  color: red;
}
.other {
  color: blue;
}
.h {
  height: 300px;
  border: 1px solid #ccc;
}
</style>

读到这里,这篇“Vue3中的模板语法和vue指令怎么使用”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI