Vue-动态绑定属性

1、v-bind基本使用

<div id="app">
  <img v-bind:src="url" alt="美女">
  <!--语法糖的写法-->
  <a :href="aHalf">百度一下</a>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'hello',
      url: 'https://gd4.alicdn.com/imgextra/i3/0/O1CN01A4OaL02FU0TNaOcHQ_!!0-item_pic.jpg',
      aHalf: 'https://www.baidu.com'
    }
  })
</script>

2、v-bind动态绑定class

  <style>
    .active{
      color: red;
    }
  </style>

<div id="app">
  <h1 :class="{active: active,line:line}">{{message}}</h1>
  <!--也可以写个方法-->
  <h1 :class="getClass()">{{message}}</h1>
  <button @click="change">点击换色</button>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'hello',
      active:true,
      line:true
    },
      methods: {
      change: function (){
        this.active = !this.active;
      },
      getClass: function (){
        return {active: this.active,line: this.line}
      }
    }
  })
</script>

3、v-for和v-bind的结合

  • 点击谁,谁变红色
  <style>
    .setRed {
      color: red;
    }
  </style>
<div id="app">
  <ul>
    <li v-for="(item,index) in movies" :class="{setRed: index == current}" @click="setColor(index)">{{item}}</li>
  </ul>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'hello',
      movies:['海尔兄弟','西游记','龙争虎斗个','三国演义'],
      current:0
    },
    methods: {
      setColor: function (index){
        this.current = index;
      }
    }
  })
</script>

4、v-bind绑定style

<div id="app">
  <h2 :style=getStyle()>{{message}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'hello'
    },
    methods: {
      getStyle: function () {
        return {
          fontSize: '50px',
          color: 'red'
        }
      }
    }
  })
</script>
posted @   JamieChyi  阅读(15)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示