一. 模板语法
1. 文本
<span>Message: {
{ msg }}</span>
msg
属性发生了改变,插值处的内容都会更新。
如果只想更新一次: v-once
<span v-once>这个将不会改变: {
{ msg }}</span>
2. HTML
双大括号会将数据解释为普通文本,而非 HTML 代码。为了输出真正的 HTML,你需要使用f="https://cn.vuejs.org/v2/api/#v-html">v-html指令
例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<p>Using mustaches: {
{ rawHtml }}</p>
<!-- 这个会被解析成文本 -->
<p><span v-html='rawHtml'></span></p>
<!-- 这个会被解析成HTML -->
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
rawHtml:'<span style="color: red;">this should be red</span>'
},
})
</script>
</body>
</html>
![aa0a3bcf4e1fc567976609ec00fb8e60.png](https://img-blog.csdnimg.cn/img_convert/aa0a3bcf4e1fc567976609ec00fb8e60.png)
3.绑定标签属性
Mustache 语法不能作用在 HTML attribute 上,遇到这种情况应该使用f="https://cn.vuejs.org/v2/api/#v-bind">v-bind指令
<div v-bind:id="dynamicId"></div>
对于布尔 attribute (它们只要存在就意味着值为true
),v-bind
工作起来略有不同,在这个例子中:
<button v-bind:disabled="isButtonDisabled">Button</button>
如果isButtonDisabled
的值是null
、undefined
或false
,则disabled
attribute 甚至不会被包含在渲染出来的<button>
元素中。
4. { {}} 和v-bind其实都可以用JavaScript表达式
有个限制就是,每个绑定都只能包含单个表达式
{
{ number + 1 }}
{
{ ok ? 'YES' : 'NO' }}
{
{ message.split('').reverse().join('') }}
<div v-bind:id="'list-' + id"></div>
-------------------------------------------------------------------------------------
<!-- 这是语句,不是表达式 -->
{
{ var a = 1 }}
<!-- 流控制也不会生效,请使用三元表达式 -->
{
{ if (ok) { return message } }}
二. 指令
![e90e05213a00986820a0178ccefb85b2.png](https://img-blog.csdnimg.cn/img_convert/e90e05213a00986820a0178ccefb85b2.png)
指令 (Directives) 是带有v-
前缀的特殊 attribute。比如: v-on v-if v-bind 等等