上期回顾:Vue简介、引入、命令式和声明式编程

一、Mustache插值语法

mustache 语法: 是"胡子"的意思, 据说是因为嵌入标记像胡子 {{}}(我觉得一点也不像哎O(∩_∩)O哈哈~)

把数据显示到模板(template)中,使用最多的语法是 “Mustache”语法 (双大括号) 的文本插值

  • data返回的对象是有添加到Vue的响应式系统中;
  • 当data中的数据发生改变时,对应的内容也会发生更新。
  • Mustache中不仅仅可以是data中的属性,也可以是一个JavaScript的表达式

我们可以写:

  • 表达式
  • 三元表达式
  • 调用methods中函数
 <div id="app">
<h2>{{message}}</h2>
<h2>当前计数:{{counter}}</h2>
<!-- 2.表达式 -->
<h2>计数双倍:{{counter*2}}</h2>
<h2>展示的信息:{{info.split(" ")}}</h2>
<!-- 3.三元表达式 -->
<h2>{{age>=18?"成年人" : "未成年人"}}</h2>
<!-- 4.调用methods中函数 -->
<h2>{{formatDate(time)}}</h2>
</div>

 二、v-bind的绑定属性

2.1.v-bind绑定基本属性

单向绑定v-bind:数据只能从data流向页面

绑定属性我们可以使用v-bind,比如动态绑定a元素的href属性、img元素的src属性

v-bind用于

  • 绑定一个或多个属性值
  • 向另一个组件传递props值**(props:相当于一个组件的输入,后面会学习到的)

v-bind:href 可以写为 :href 这就是v-bind的语法糖

<div id="app">
<!-- 1.绑定img的src属性 -->
<button @click="switchImage">切换图片</button>
<img v-bind:src="https://www.jb51.net/article/showImgUrl" alt="" />
<!--语法糖 v-bind: = :  -->
<!-- 2.绑定a的href属性 -->
<a v-bind:href="https://www.jb51.net/article/href" rel="external nofollow" >百度一下</a>
</div>

2.2.v-bind绑定class

基本绑定class

<h2 :class="classes">Hello World</h2>

动态class可以写对象语法

<button :class="isActive ? 'active':''" @click="btnClick">
我是按钮
</button>

对象语法的基本使用

<button :class="{active:isActive}" @click="btnclick">我是按钮</button>

对象语法的多个键值对,动态绑定的class是可以和普通的class同时的使用

  • 我们可以给v-bind:class一个对象,用以动态的切换class
  • 当然,v-bind:class也是可以与普通的class特性共存
<button class="abc cba" :class="getDynamicClasses" @click="btnClick">
我是按钮
</button>

 2.3.v-bind绑定style

普通的html写法

<h2>hhh</h2>

style中的某些值,来自data中

动态绑定style,在后面跟上对象类型

<h2 v-bind:style="{color:fontColor,fontSize:fontSize}">hhhh</h2>

动态的绑定属性,这个属性是一个对象

<h2 :style="objStyle">hhhhh</h2>

2.4.v-bind绑定属性名

绑定data中的属性名

在属性名不是固定的情况下使用:[属性名]=“值”

<div id="app">
<h2 :[name]="aaaa">Hello World</h2>
</div>
<script src="https://www.jb51.net/lib/vue.js"></script>
<script>
const app = Vue.createApp({
data: function () {
return {
name: "class",
};
},
});
app.mount("#app");

2.5.v-bind直接绑定对象

传入一个对象,对象来自于data,一个对象的所有属性,绑定到元素上的所有属性

<div id="app">
<h2 :name="name" :age="age" :height="height">Hello world</h2>
<--直接绑定一个对象,一步到位-->
<h2 v-bind="infos"></h2>
</div>
<script src="https://www.jb51.net/lib/vue.js"></script>
<script>
const app = Vue.createApp({
data: function () {
return {
infos: { name: "kk", age: 18, height: 1.7 },
name: "kk",
age: 18,
height: 1.7,
};
},
});
app.mount("#app");

总结

到此这篇关于Vue中Mustache插值语法与v-bind指令的文章就介绍到这了,更多相关VueMustache插值与v-bind指令内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。