开始
删除Helloworld.vue
还原App.vue为如下
<script setup>
</script>
<template>
</template>
<style scoped>
</style>
运行项目
yarn dev
浏览器打开http://localhost:5173/
为一片空白,则为下面的教程做准备
模板语法
dom插入变量
- 例子
<h1>a的值为: {{ a }}</h1>
- 完整代码(通过双大括号来引用a,同时每次 a 属性更改时它也会同步更新)
<script setup>
import { ref } from 'vue';
const a = ref(0)
</script>
<template>
<h1>a的值为: {{ a }}</h1>
</template>
<style scoped>
</style>
- 显示
插入变量为html
- 例子
<h1 v-html="a"></h1>
- 完整代码(通过属性v-html来引用a,同时每次 a 属性更改时它也会同步更新)
<script setup>
import { ref } from 'vue';
const a = ref(`<a href='https://www.baidu.com'>一个链接</a>`)
</script>
<template>
<h1 v-html="a"></h1>
</template>
<style scoped>
</style>
- 显示
变量绑定dom元素属性
- 例子
<h1 :id="a" :class='a' :style='a' ></h1>
- 完整代码(通过双大括号来引用a显示到dom,通过在元素属性前面加冒号( : )来绑定a的值,同时每次 a 的值更改时它也会同步更新)
<script setup>
import { ref } from 'vue';
const a = ref('id-1')
</script>
<template>
<h1 :id="a">id 为 {{ a }} 的元素</h1>
</template>
<style scoped>
#id-1{
color:#ff0000;
border:5px solid #00ff00
}
</style>
- 显示
引用函数
- 例子
<h1>{{ func() }}</h1>
- 完整代码(通过双大括号来引用函数func显示到dom,通过在元素属性前面加冒号( : )来绑定func()的值)
<script setup>
import { ref } from 'vue';
const func = function(){
for(var i=0;i<100;i++);
return i;
}
</script>
<template>
<h1 id='id-1'>函数func运行完为 {{ func() }}</h1>
</template>
<style scoped>
#id-1{
color:#ff0000;
border:5px solid #00ff00
}
</style>
- 显示
使用 JS 表达式
- 例子
<h1>{{ a ? '是' : '否' }}</h1>
- 完整代码(通过双大括号来引用js表达式显示到dom,表达式可以是三元操作符 也可以是 对象方法,同时每次 a 的值更改时它也会同步更新)
<script setup>
import { ref } from 'vue';
const a = ref(true)
</script>
<template>
<h1 id='id-1'>a的值为true: {{ a ? '是' : '否' }}</h1>
<h1 id='id-1'>a的值为{{ a.toString() }}</h1>
</template>
<style scoped>
#id-1{
color:#ff0000;
border:5px solid #00ff00
}
</style>
- 显示
绑定点击事件
- 例子
<h1 @click='add'>{{ a }}</h1>
- 完整代码(通过@符号来绑定对应事件,@click绑定时,点击对于dom元素,a会对应更改,同时每次 a 的值更改时它也会同步更新)
<script setup>
import { ref } from 'vue';
const a = ref(0)
const add = ()=>{
a.value += 1
}
const sub = ()=>{
a.value -= 1
}
</script>
<template>
<h1 id='id-1' @click='add'>a的值为{{ a }}, 点我a加一</h1>
<button @click='sub'>点我a减1</button>
</template>
<style scoped>
#id-1{
color:#ff0000;
border:5px solid #00ff00
}
</style>
- 显示
动态参数
- 例子
<h1 :[attr1]='a' @[attr2]='func'>{{ a }}</h1>
- 完整代码(这里与上一目录[绑定点击事件] 章节效果一模一样,只是这节使用中括号( [] ) 来使用动态参数)
<script setup>
import { ref } from 'vue';
const a = ref(0)
const attr1 = ref('id')
const attr2 = ref('click')
const add = ()=>{
a.value += 1
}
const sub = ()=>{
a.value -= 1
}
</script>
<template>
<h1 :[attr1]='"id-1"' @[attr2]='add'>a的值为{{ a }}, 点我a加一</h1>
<button @[attr2]='sub'>点我a减1</button>
</template>
<style scoped>
#id-1{
color:#ff0000;
border:5px solid #00ff00
}
</style>
- 显示