目录:
一、插值
- 文本
- 原始的 html
- 特性
- 动态参数
- js 表达式
1.文本
文本这个最简单,就是数据是什么,模板中就渲染什么。
示例代码:
<body>
<div id="app">
<!-- this is a test -->
{{ message }}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el : '#app',
data : {
message : 'this is a test'
}
})
</script>
</body>我们可以使用 v-once 指令,规定数据只渲染一次。写法如下:<div id="app">
<!-- this is a test -->
<p v-once>{{ message }}</p>
</div>v-cloak 指令,用来控制当数据没有渲染出来的时候,是否显示占位符。需要注意,该指令要和 css 配合使用。html 部分:
<body>
<div id="app">
<!-- this is a test -->
<p v-cloak>{{ message }}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el : '#app',
data : {
message : 'this is a test'
}
})
</script>
</body>
css 部分:
<style>
[v-cloak]{
display: none;
}
</style>
2. 原始的 html
有些时候我们渲染的数据,含有 html 标签,但是如果以文本的形式,无法渲染出 html所以需要使用 v-html 指令。
示例如下:
<body>
<div id="app">
<!-- this is a test -->
<p>{{ message }}</p>
<p v-html="message"></p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el : '#app',
data : {
message : '<span style="color:red">this is a test</span>'
}
})
</script>
</body>
3. 特性
所谓特性,就是 html 标签中动态的属性,换句话说,就是 html 中的属性通过 data 来控制。
示例代码如下:
<body>
<div id="app">
<!-- this is a test -->
<p v-bind:title='abc'>{{ message }}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el : '#app',
data : {
message : 'this is a test',
abc : 'this is a title'
}
})
</script>
</body>
绑定有一个简写的方法,将 v-bind 简写为一个 ":"
<p :title='abc'>{{ message }}</p>
4. 动态参数
该功能是 vue 2.6.0 以后所提供的功能。绑定的属性名可以是动态的。
实例代码如下:
<body>
<div id="app">
<!-- this is a test -->
<p :[title]='abc'>{{ message }}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el : '#app',
data : {
message : 'this is a test',
abc : 'this is a title',
title : 'title'
}
})
</script>
</body>
5. 使用 js 表达式
在我们的占位符里面,可以放入 js 表达式。最终,模板里面会显示表达式的返回值。
示例代码如下:
<body>
<div id="app">
<p>{{num + 1}}</p>
<p>{{ ok ? 'Yes' : 'No' }}</p>
<p>{{ message.split('').reverse().join('')}}</p>
<p :id="'list'+id"></p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el : '#app',
data : {
num : 1,
ok : true,
message : 'this is a test',
id : 1
}
})
</script>
</body>