Vue-v-bind的基本使用

1. v-bind的基本使用

  在开发的时候,有时候我们的属性不是写死的,有可能是根据我们的一些数据动态地决定的,比如图片标签(<img>)的src属性,我们可能从后端请求了一个包含图片地址的数组,需要将地址动态的绑定到src上面,这时就不能简单的将src写死。还有一个例子就是a标签的href属性。这时可以使用v-bind指令:

  作用:动态绑定属性;

  缩写(语法糖):: (只用一个冒号代替);

  预期:

    (1)any (with argument),任意参数;

    (2)Object (without argument),对象 。

  参数:attrOrProp (optional)

  例子1:其中,v-bind可以缩写成:

  

 服务器请求过来的数据,我们一般都会在data那里做一下中转,做完中转过后再把需要的变量绑定到对应的属性上面。

2. v-bind动态绑定属性class

  v-bind除了在开发中用在有特殊意义的属性外(src, href等),也可以绑定其他一些属性,如class。

  例子:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>Title</title>
 6   <style>
 7     .active {
 8       color: red;
 9     }
10   </style>
11 </head>
12 <body>
13   <div id="app">
14     <h2 class="title" v-bind:class="{active: isActive, line: isLine}">{{message}}</h2>
15     <h2 class="title" v-bind:class="['active', 'line']">{{message}}</h2>
16     <h2 class="title" v-bind:class="getClassesArray()">{{message}}</h2>
17 
18     <button v-on:click="btnClick">按钮</button>
19   </div>
20 
21     <script src="../js/vue.js"></script>
22     <script>
23       const app = new Vue({
24         el: '#app',
25         data: {
26           message: '你好啊',
27           active: 'active',
28           line: 'line',
29           isActive: true,
30           isLine: true,
31         },
32         methods: {
33           btnClick: function () {
34             this.isActive = !this.isActive;
35           },
36           getClasses: function () {
37             return {active: this.isActive, line: this.isLine};
38           },
39           getClassesArray: function () {
40             return [this.active, this.isLine];
41           }
42         }
43       });
44     </script>
45 </body>
46 </html>

打开的效果:

 点击按钮之后,效果如下:

 这个按钮的作用就是取反。

3. 练习作业

  动态绑定的一个小作业,需求是:点击列表中的哪一项,那么该选项的文字变成红色,背景变为浅灰色。直接贴上代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>Title</title>
 6   <style>
 7     .active {
 8       color: red;
 9       background-color: lightgray;
10     }
11   </style>
12 </head>
13 <body>
14   <div id="app">
15 
16     <ul>
17       <li v-for="(item, index) in movies" v-on:click="changeColor(index)">
18         <div v-bind:class="{active: currentIndex == index}">{{index}}-{{item}}</div>
19       </li>
20     </ul>
21 
22   </div>
23 
24     <script src="../js/vue.js"></script>
25     <script>
26       const app = new Vue({
27         el: '#app',
28         data: {
29           message: '你好啊',
30           movies: ['海王', '海尔兄弟', '火影忍者', '进击的巨人'],
31           currentIndex: Number.MIN_VALUE,
32         },
33         methods: {
34           changeColor: function (index) {
35             this.currentIndex = index;
36           }
37         }
38       });
39     </script>
40 </body>
41 </html>

博客日常记录我的学习内容,如果有错误欢迎指出。

猜你喜欢

转载自www.cnblogs.com/ongiao/p/12141980.html