目录
插值语法
- 多数情况下,
Vue.js 3使用HTML模板(template)语法,通过声明式将组件开发实例的数据与DOM绑定在一起。模板语法的核心是插值(mustache)语法和指令。在Vue.js 3中,要将数据显示到模板中,常见的方式是使用插值语法,也称双大括号语法 - 下面的代码演示了插值语法的具体应用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app"></div>
<template id="my-app">
<h4> {
{ message }} - {
{ isShow }}</h4>
<h4> {
{ counter * 100 }}</h4>
<h4> {
{ message.split(" ").join(",")}}</h4>
<h4> {
{ getReverseMessage() }} </h4>
<h4> {
{ isShow ? "三元运算符": ""}}</h4>
<button @click="toggle">切换控制显示</button>
</template>
<script src="./js/vue.js"></script>
<script>
const App = {
template: '#my-app',
data() {
return {
message: 'Hello World',
counter: 100,
isShow: true,
}
},
methods: {
getReverseMessage() {
return this.message.split(" ").reverse().join(" ")
},
toggle() {
this.isShow = !this.isShow
}
}
}
Vue.createApp(App).mount('#app')
</script>
</body>
</html>
-
效果如下

-
上述例子说明插值语法支持绑定
data中的属性、还支持javascript表达式、调用方法、三元运算符等
基本指令
- 在
template中,我们会经常看到以v-开头的属性(attribute),它们被称为指令,通常,指令带有前缀v-,意味着这是Vue.js 3提供的特殊属性。它们会在渲染的DOM上应用特殊的响应式行为。下面介绍几种常见的指令
v-once
v-once指令用于指定元素或组件只渲染一次。当数据发生变化时,元素或组件及其所有的子组件将被视为静态内容,跳过更新。通常在需要进行性能优化时使用v-once指令
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app"></div>
<template id="my-app">
<h2>h2 : {
{ counter }}</h2>
<!-- 下面的内容只会被渲染一次-->
<h3 v-once>h3 : {
{ counter }}</h3>
<div v-once>
<h4>h4 : {
{ counter }}</h4>
<h5>h5 : {
{ message }}</h5>
</div>
<!-- 点击触发重新渲染-->
<button @click="increment">+1</button>
</template>
<script src="./js/vue.js"></script>
<script>
const App = {
template: "#my-app",
data() {
return {
counter: 100,
message: "Hello World!"
}
},
methods: {
increment() {
this.counter += 1
}
}
}
Vue.createApp(App).mount("#app")
</script>
</body>
</html>
- 效果如下,只有
<h2>标签的元素会被重新渲染,其他的都只渲染一次

v-text
v-text指令用于更新元素的textContent,也就是说,实际上v-text指令就相当于插值语法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app"></div>
<template id="my-app">
<!-- 这两种用法效果一样-->
<h2 v-text="message"></h2>
<h2> {
{ message }}</h2>
</template>
</body>
<script src="./js/vue.js"></script>
<script>
const App = {
template: '#my-app',
data()

最低0.47元/天 解锁文章
557





