v-bind绑定属性

mustache语法只能在html标签内部使用,标签的属性中不能使用mustache语法。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="app">
  <h2>{{message}}</h2>
  <img src="{{imagURL}}" alt="">
  <img :src="imagURL" alt="">
</div>

<script src="../vue.js"></script>
<script>
  // {{}}mustache语法只能在标签内部使用。  不用用在标签的属性绑定。
  const app = new Vue({
    el: '#app',
    data: {
      message: 'hello',
      imagURL: 'http://www.zhoushan.host/static/stark/imgs/abc.png'
    }
  })
</script>
</body>
</html>

mustache只能用在标签内部,不能作为绑定属性使用

v-bind可以实现动态属性绑定

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .active{
      color: red;
    }
    .font{
      font-size: small;
    }
  </style>
</head>
<body>
<div id="app">
  <h2 :class="{active:isActive,font:isFont}">{{message}}</h2>
</div>
<script src="../vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好,hello',
      isActive: true,
      isFont: true
    }
  })
</script>
</body>
</html>

作业,动态切换class属性。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .active{
      color: red;
    }
  </style>
</head>
<body>
<div id="app">
    {{message}}
  <ul>
    <li v-for="(item,index) in movies" @click="addButton(index)" :class="{active: position === index}">{{item}}</li>
  </ul>
</div>
<script src="../vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'hello',
      movies: ['我是谁','天地英雄','肖生克的救赎'],
      position: '',

    },
    methods: {
        addButton(i) {
          console.log('点击了',i)
          this.position = i
        }
      },
  })
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/ch2020/p/14815191.html