vue学习笔记总结(v-bind动态绑定属性)

v-bind

1. v-bind基本使用

v-bind用于绑定数据和元素属性,可以使用:简写

<div id="app">
    <img v-bind:src="imgURL" alt="">
    <a v-bind:href="aHerf">a>
    
    <img :src="imgURL" alt="">
    <a :href="aHerf">a>
div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">script>
<script>
    const app = new Vue({
      el:"#app",
      data:{
        message:"你好啊",
        imgURL:"https://cn.bing.com/th?id=OIP.NaSKiHPRcquisK2EehUI3gHaE8&pid=Api&rs=1",
        aHerf:"http://www.baidu.com"
      }
    })
script>

2. v-bind动态绑定class

  • 对象语法

通过v-bind指令可以为DOM元素动态绑定class

比如给

标签动态添加一个class = active,active修改文字颜色为红色,点击按钮控制active是否绑定,实现文字颜色的切换。


<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>v-bind动态绑定class(对象语法)title>
  <style>
    .active{
      color:red;
    }
  style>
head>
<body>
  <div id="app">
    
    
    <h2 class="title" :class="{active:isActive}">{{message}}h2>
    <h2 class="title" :class="getClasses()">{{message}}h2>
    <button @click="change">点击变色button>
  div>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">script>
  <script>
    const app = new Vue({
      el:"#app",
      data:{
        message:"你好啊",
        active:"active",
        isActive:true
      },
      methods: {
        change(){
          this.isActive = !this.isActive
        },
        getClasses(){
          return {active:this.isActive}
        }
      },
    })
  script>
body>
html>
  • 数组语法
<div id="app">
    
    <h2 class="title" :class="['active','line']">{{message}}h2>
    
    <h2 class="title" :class="[active,line]">{{message}}h2>
    <h2 class="title" :class="getClasses()">{{message}}h2>
div>

<script>
    const app = new Vue({
      el:"#app",
      data:{
        message:"你好啊",
        active:"aaaa",
        line:'bbbb'
      },
      methods: {
        getClasses(){
          return [this.active,this.line]
        }
      },
    })
script>

v-bind动态绑定style

  • 对象语法


<h2 :style="{fontSize:'50px'}">{{message}}h2>

<h2 :style="{fontSize:fontSize}">{{message}}h2>
<h2 :style="getStyle()">{{message}}h2>
  • 数组语法
<div id="app">
  <h2 :style="[baseStyle]">{{message}}h2>
  <h2 :style="getStyle()">{{message}}h2>
div>
<script>
const app = new Vue({
  el:"#app",
  data:{
    message:"你好啊",
    baseStyle:{backgroundColor:'red'}
  },
  methods: {
    getStyle(){
      return [this.baseStyle]
    }
  },
})
script>

你可能感兴趣的:(vue,javascript,html,js,class)