3. vue2 绑定属性 绑定Html 绑定class 绑定style

一、 绑定属性

<template>
  <div>
    <!-- 绑定属性 -->
    <img v-bind:src="url" v-bind:title="title" />
    <img :src="url" :title="title" />
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      title: "这是一张测试图片",
      url: "https://www.itying.com/themes/itying/images/logo.gif",
    };
  },
};
</script>

二、 绑定Html

<template>
  <div>
    <!-- 差值表达式会以文本的方式呈现html -->
    {{ h }}
    <!-- 绑定html -->
    <div v-html="h"></div>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      h: "<h2>html 内容测试</h2>",
    };
  },
};
</script>

三、 绑定class

3.1 字符串写法

  • 使⽤场景
    样式的类型不确定
<div :class="xg">test</div>
  • ⼿动触发样式改变
  • 字符串使⽤的是vue实例data中的已有属性

3.2 对象写法

  • 使⽤场景
    样式个数、类名确定,通过Boolean动态展示与否
  • 对象写在内联样式
<div :class="{bg_red:bg_red,border:border}">test</div>
  • 对象写在data中
<div :class="list">test</div>
data: {
list: {
bg_red: 'bg_red',
border: 'border',
 },
}

3.3 数组写法

  • 使⽤场景
    需要绑定的样式个数不确定,类名也不确定
  • 内联写法
<div :class="[xd_border,xd_bg]">test</div>
  • 数组⾥加三元表达式
<div :class="[isActive?xd_border:'',xd_bg]">test</div> 
  • 写在data中
<div :class="list">test</div>
data:{
 list:['border', 'bg_red']
}
<template>
  <div>
    <!-- 绑定 class -->
    <ul>
      <li
        v-for="(item, key) in list"
        :class="{ red: key == 0, blue: key == 1 }"
      >
        {{ key }}---{{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      list: ["1111", "2222", "3333"],
    };
  },
};
</script>

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

四、 绑定style

<template>
  <div>
    <!-- v-bind:style  :style的使用 -->
    <div class="box" v-bind:style="{ width: boxWdith1 + 'px' }">
      我是一个div
    </div>
    <div class="box" :style="{ width: boxWdith2, background: 'blue' }">
      我是另一个div
    </div>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      boxWdith1: 500,
      boxWdith2: "300px",
    };
  },
};
</script>

<style>
.box {
  height: 100px;
  width: 100px;
  background: red;
}
</style>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值