亲宝软件园·资讯

展开

vue3模板语法和vue指令

LotusFlower 人气:0

1 模板插值语法

<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-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="style">绑定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>

加载全部内容

相关教程
猜你喜欢
用户评论