让“Hello Vue”与多个属性进行绑定,我们可以用v-bind指令
如下代码,
<div id="app">
<h2 v-bind:class="styleA">{{message}}</h2>
<h2 v-bind:id="att.id" v-bind:class="att.class">{{message}}</h2>
<div v-bind="att">我是div</div>
<button click="changeStyle">按钮</button>
</div>
<script type="text/javascript" src="./js/vue.global.js"></script>
<script>
// 1.创建app
const app = Vue.createApp({
// data: option api
data: function() {
return {
message: "Hello Vue",
styleA:'green',
att:{
id:"box",
class:"red"
}
}
},
methods: {
changeStyle(){
}
}
})
// 2.挂载app
app.mount("#app")
</script>
<style>
.red{
color: red;
font-size: 20px;
}
.green{
color:green;
font-size: 20px;
}
</style>
我们可以通过v-bind来让message对象与red,green属性绑定
<h2 v-bind:id="att.id" v-bind:class="att.class">{{message}}</h2>
这样message就对象就有了red和green属性。
class绑定的写法:
第一种写法:字符串(data变量名):样式类名不确定,个数确定
<h2 :class="styleA">{{message}}</h2>
第二种写法:对象:{boolean变量}:类名确定,类的个数也确定,是否使用不确定
<h2 :class="{red:isUse}">{{message}}</h2>
三目运行写法
<h2 :class="isUse?'red':'green'">{{message}}</h2>
数组写法
<h2 :class="['red,'bg',styleA,{'size':isUse}]">{{message}}</h2>
在style绑定中样式属性名则要使用小驼峰的写法,即复合单词的后一个单词的首字母要大写;样式与样式之间要用逗号隔开。
例如: <div :style="{ 'font-size': fSize + 'px' }"></div>