Vue 3教程02 - 绑定数据及样式


绑定文字

两种方式:

  • 使用
  • 使用v-text:很少使用
markup
<template>
  <div>Hello, {{ name }}</div>
  <div v-text="name"></div>
</template> 

<script>
export default {
  name: "App",
  data() {
    return {
      name: "逻思编程",
    }
  }
}
</script>  

Binding HTML

markup
<div v-html="name"></div>

需要注意,在使用v-html的时候,只能在数据来源可靠时使用,否则可能会遭受XSS攻击。比如:在第三方API返回的数据中可能包含恶意代码,这时不要使用v-html。

Binding to attributes

markup
<template>
  <button v-bind:disabled="isDisabled">提交</button>
</template>  

<script>
  // ...
  data() {
    return {
      // ...
      isDisabled: true,
    }
  }
</script>  

Binding classes

使用静态类

markup
<template>
  <div class="myclass">
  </div>  
</template>

<style>
  .myclass {
    ...
  }
</style>  

动态绑定可以和静态类结合使用:

markup
<template>
  <div class="myclass" v-bind:class="status">
  </div>  
</template>

<script>
  ...
  data() {
    return {
      status: "warning"
    }
  }
</script>  

在v-bind中,还可以进行逻辑判断:

markup
<div v-bind:class="registered? 'done' : 'inprogress'">

可以同时指定不同的类:

markup
<div v-bind:class="['class1', 'class2']">

使用对象来动态绑定类:

markup
<div v-bind:class="{
  'done': registered
}">

Binding styles

在script部分定义对应变量:

JavaScript
data() {
  return {
    myColor: 'blue',
    myFontSize: 20,
    myStyleObj: {
      color: 'blue',
      fontSize: '20px',
      padding: '10px'
    }
  }
}
markup
<div v-bind:style="{
  color: myColor,
  'font-size': myFontSize + 'px',
  padding: '10px'
}">
</div>

<div v-bind:style="myStyleObj">
</div>  

也可以通过数组绑定多个样式类:

markup
<div v-bind:style="[style1, style2]">

需要注意,所有的v-bind都可以被省略掉,比如:

markup
<div :style="[style1, style2]">

文章作者: 逻思
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 逻思 !