vue v-bind绑定属性和样式

时间:2023-03-09 20:32:18
vue v-bind绑定属性和样式

这期跟大家分享的,是v-bind指令。它可以往元素的属性中绑定数据,也可以动态地根据数据为元素绑定不同的样式。

绑定属性

最简单的例子,我们有一张图片,需要定义图片的src。我们可以直接在元素的属性里面定义:

<div id="app">
<img src="https://cn.vuejs.org/images/logo.png" alt="">
</div> <!-- ... ... --> <script type="text/javascript">
var app = new Vue({
el: '#app'
});
</script>

但是在实际工作中,我们通常会遇到的情况是,图片地址是从数据里返回的,这个时候v-bind指令就派上了用场。当然,我们可以同时绑定各种属性:

<div id="app">
<img v-bind:src="imgSrc" v-bind:alt="imgAlt" v-bind:title="imgTitle">
</div> <!-- ... ... --> <script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
imgSrc: 'https://cn.vuejs.org/images/logo.png',
imgAlt: 'vue-logo',
imgTitle: '这是你指定的title,主人'
}
});
</script>

在浏览器可以看到效果:

vue v-bind绑定属性和样式

这时候你也许会说,每次都要写一遍v-bind好麻烦。没问题,Vue为你准备好了简写的方式:

<div id="app">
<img :src="imgSrc" :alt="imgAlt" :title="imgTitle">
</div>

绑定行内样式

v-bind也可以用于绑定样式,使用行内样式时,关键字是style,跟在html里面直接写行内样式类似。注意样式的写法跟css会有些许不同,横杠分词变成驼峰式分词。

<div id="app">
<button class="btn" :style="{ color: 'white', backgroundColor: 'blue' }">点击我吧,主人!</button>
</div>

当然,把样式写在vue的data里面会方便一些:

<div id="app">
<button class="btn" :style="styles">点击我吧,主人!</button>
</div> <!-- ... ... --> <script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
styles: {
color: 'white',
backgroundColor: 'blue'
}
}
});
</script>

在浏览器中可以看到html中的行内样式:

vue v-bind绑定属性和样式

绑定CSS样式

更常见的做法肯定是根据数据绑定不同的样式了。这时关键字是class。【注意:v-bind:class指令可以与普通的class特性共存】

<style>
.is-active {
color: white;
background-color: green;
}
</style> <body>
<div id="app">
<!-- 根据数据中isActive来决定是否把is-active这个class加给元素 -->
<button class="btn" :class="{ 'is-active': isActive }">点击我吧,主人!</button>
</div> <!-- ... ... --> <script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
isActive: true
}
});
</script>
</body>

效果如图:

vue v-bind绑定属性和样式

当然,在实际工作中isActive的值一般不会像例子中这样直接写死,而是根据用户的交互或者数据进行判断。

摘https://segmentfault.com/a/1190000008159046