vue.js 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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值