vue3(一)模板插值语法和指令

533 阅读1分钟

模板插值语法

在script中声明一个变量,可以直接在template中使用。

<template>
  <h1>{{ msg }}</h1>
</template>

<script setup lang="ts">

const msg = 123

</script>

<style scoped></style>

也可以使用条件运算

<template>
  <h1>{{ msg ? '111' : '222' }}</h1>
</template>

<script setup lang="ts">

const msg = 123

</script>

<style scoped></style>

操作api

<template>
  <h1>{{ msg.split(',') }}</h1>
  <h1>{{ msg2.join('-') }}</h1>
</template>

<script setup lang="ts">

const msg = "1,2,3"
const msg2 = ['1', '2', '3']

</script>

<style scoped></style>

vue指令

v- 开头的都是vue的指令

v-text  // 用来显示文本
v-html  // 内容按普通html插入
v-show  // 通过传入值的真假,改变元素可见,相当于css中的display:none/block
v-if  // 通过传入值的真假,判断是否渲染元素
v-else/v-else-if // 表示 v-if 或 v-if / v-else-if 链式调用的“else 块”。
v-for  // 基于数据遍历元素
v-on 简写:'@'  // 给元素绑定事件监听器
v-on修饰符
    .stop - 调用 event.stopPropagation()。
    .prevent - 调用 event.preventDefault()。
    .capture - 在捕获模式添加事件监听器。
    .self - 只有事件从元素本身发出才触发处理函数。
    .{keyAlias} - 只在某些按键下触发处理函数。
    .once - 最多触发一次处理函数。
    .left - 只在鼠标左键事件触发处理函数。
    .right - 只在鼠标右键事件触发处理函数。
    .middle - 只在鼠标中键事件触发处理函数。
    .passive - 通过 { passive: true } 附加一个 DOM 事件。

v-bind 简写:':'  // 动态绑定元素的attribute
v-model  // 在表单输入元素或组件上创建双向绑定。
v-slot  // 插槽
v-once // 性能优化,仅渲染元素和组件一次,并跳过之后的更新。
v-pre // 跳过元素及其所有子元素的编译

案例

阻止事件冒泡,使用修饰符'@click.stop="xxx"'

<template>
  <div class="parent" @click="parent">
    <div class="child" @click.stop="child">child</div>
  </div>
</template>

<script setup lang="ts">

const parent = () => {
  console.log('执行了parent');
}

const child = () => {
  console.log('执行了child');
}
</script>

<style scoped>
.parent {
  width: 200px;
  height: 200px;
  background-color: red;
}

.child {
  width: 150px;
  height: 150px;
  background-color: rgb(54, 88, 189);
}
</style>

阻止表单默认事件 .prevent

<template>
  <form action="/">
    <button @click.prevent="submit" type="submit">submit</button>
  </form>
</template>

<script setup lang="ts">

const submit = () => {
  console.log('执行了submit');
}

</script>

<style scoped></style>