vue动态绑定属性--基本用法及动态绑定class

vue

动态绑定属性v-bind:,语法糖形式:省略v-bind,仅写一个冒号。

一、动态绑定基本属性

 1 <body>

2 <!-- v-bind 动态绑定属性-基本用法 -->

3 <img v-bind:src="imgUrl" alt="">

4 <script src="../js/vue.js"></script>

5   <script>

6  setTimeout(function() {

7  const vm = new Vue({

8 el: '#app',

9 data: {

10 imgUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F4k%2Fs%2F02%2F2109242332225H9-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1650099133&t=7737c14262a80534f32b81b3210ae247',

11 },

12 });

13 },2000);

14 </script>

15 </body>

二、动态绑定class

(1)基本用法:

 1 <head>

2 <style>

3 .active{

4 color: red;

5 }

6 </style>

7 </head>

8

9 <body>

10 <div id="app">

11

12 <!-- v-bind动态绑定class--基本用法 -->

13 <div class="active">{{msg}}</div>

14 <div :class="on">{{msg}}</div>

15

16 </div>

17 <script src="../js/vue.js"></script>

18 <script>

19 setTimeout(function() {

20 const vm = new Vue({

21 el: '#app',

22 data: {

23 msg: 'hello',

24 on: 'active',

25 }

26 });

27 },2000);

28 </script>

29 </body>

(2)对象语法:

  a.语法格式:v-bind:class="{类名1:布尔值,类名2:布尔值}"

 1 <head>

2 <style>

3 .active{

4 color: red;

5 }

6 </style>

7 </head>

8

9 <body>

10 <div id="app">

11

12 <!-- v-bind动态绑定class--对象语法(使用较多) -->

13 <div :class="{active:isActive,line:isLine}">{{msg}}</div>

14

15 </div>

16 <script src="../js/vue.js"></script>

17 <script>

18 setTimeout(function() {

19 const vm = new Vue({

20 el: '#app',

21 data: {

22 msg: 'hello',

23 isActive: false,

24 isLine: true,

25 }

26 });

27 },2000);

28 </script>

29 </body>

30

  b.如果绑定的对象太长,可以放在方法或者是计算属性中,将其返回,调用方法时必须加上括号

 1 <head>

2 <style>

3 .active{

4 color: red;

5 }

6 </style>

7 </head>

8

9 <body>

10 <div id="app">

11

12 <div :class="getClassesObj()">{{msg}}</div>

13

14 </div>

15 <script src="../js/vue.js"></script>

16 <script>

17 setTimeout(function() {

18 const vm = new Vue({

19 el: '#app',

20 data: {

21 isActive: false,

22 isLine: true

23 },

24 methods: {

25 getClassesObj(){

26 return {active: this.isActive, line:this.isLine};

27 }

28 }

29 });

30 },2000);

31 </script>

32 </body>

(3)数组语法

 1 <head>

2 <style>

3 .active{

4 color: red;

5 }

6 </style>

7 </head>

8

9 <body>

10 <div id="app">

11

12 <!-- v-bind动态绑定class--数组语法(少) -->

13 <h1 :class="['active', 'line']"></h1>

14 <h1 :class="[active, line]">v-bind动态绑定class--数组语法(少)</h1>

15 <h1 :class="getClassesArr()">v-bind动态绑定class--数组语法(少)-方法</h1>

16

17 </div>

18 <script src="../js/vue.js"></script>

19 <script>

20 setTimeout(function() {

21 const vm = new Vue({

22 el: '#app',

23 data: {

24 msg: 'hello',

25 active: 'aaa',

26 line: 'bbb',

27 },

28 methods: {

29 getClassesArr(){

30 return [this.active, this.line];

31 }

32 },

33 });

34 },2000);

35 </script>

36 </body>

37

38 </html>

以上是 vue动态绑定属性--基本用法及动态绑定class 的全部内容, 来源链接: utcz.com/z/381020.html

回到顶部