12.VUE - v-bind 詳解


v-bind指令用於給html標簽設置屬性。

<!-- 完整語法 -->
<a v-bind:href="url"></a>
<!-- 縮寫 -->
<a :href="url"></a>

v-bind入門

<div id="app">
  <div v-bind:id="id1">文字</div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    id1: 'myid'
  }
})
</script>

會渲染如下:

<div id="myid">文字</div>

字符串拼接

<span :text=' "we" + 1 '>使用</span>

會渲染如下:

<span text='we1'>使用</span>

運算:

<div :text='1 + 2'>test</div>

會渲染如下:

<div text="3">test</div>

調用函數:

 <div :text='getText()'>test</div>
 ......
 <script>
export default {
  methods: {
    getText() {
      return "this is text"
    }
  }
}
</script>

渲染成:

<div text="this is text">test</div>

使用對象:

<template>
  <div class="hello">
    <div :text='obj'>test</div>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      obj: Object()
    }
  }
}
</script>

結果:

<div text="[object Object]">test</div>

如果對象有toString方法:

<template>
  <div class="hello">
    <div :text='obj'>test</div>
  </div>
</template>

<script>
var obj = Object()
obj.toString = function(){
  return "data in obj"
}
export default {
  name: 'HelloWorld',
  data () {
    return {
      obj: obj
    }
  }
}
</script>

則渲染的是toString方法的值:

<div text="data in obj">test</div>

和數組使用:

<template>
  <div class="hello">
    <div :text='array'>test</div>
  </div>
</template>

<script>
var array = Array()
array[0] = "1"
array[1] = "2"
export default {
  name: 'HelloWorld',
  data () {
    return {
      array: array
    }
  }
}
</script>

渲染為:

<div text="1,2">test</div>

v-bind vs 計算屬性

<template>
  <div class="hello">
    <div :text='myText'>test</div>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      value: "data"
    }
  },
  computed: {
    myText: function(){
      return "value is " + this.value
    }
  }
}
</script>

稍微對比一下,我們不難發現,計算屬性和上面的各種功能是一樣的,但是在字符串拼接的情況下,使用計算屬性的好處是分離了,不在html中寫邏輯。所以計算屬性是更推薦的用法。

class 屬性綁定

<div id="app">
  <div v-bind:class="{active: isActive}">文字</div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    isActive: true
  }
})
</script>

如果同時多個類都要判斷,則可寫成<div v-bind:class="{active: isActive, highlight: isHighlight}">文字</div>

綁定computed屬性:

而且還可以綁定computed里的屬性,畢竟data的數據是靜態的,computed的屬性可以計算:

<div id="app">
  <div v-bind:class="classObject">文字</div>
</div>

<script>
new Vue({
  el: '#app',
  computed: {
    classObject: function () {
      // 計算過程省略,假設得出了isActive和isDanger的布爾值
      return {
        'active': isActive,
        'text-danger': isDanger
      }
    }
  }
})
</script>

 

參考:https://www.cnblogs.com/vuenote/p/9328401.html

參考:https://blog.csdn.net/qq_34911465/article/details/81432542

參考:https://www.jianshu.com/p/019b868c0279


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM