vue3-1-模板插值语法与动态绑定属性

938 阅读1分钟
<template>
  <h2>vue3-第一章</h2>
  <!-- 模板插值语法:两个大括号中间放js变量 -->
  <!-- 双括号中的变量的值会被解析为普通的字符串 -->
  <p>{{ myname }}</p>
  <p>{{ text }}</p>

  <!-- 双括号中可以是简单的js表达式或者函数调用 -->
  <!-- 注意:双括号中不要放过多的js表达式,否则会模板过重,难以维护 -->
  <p>{{ 1 > 2 ? '你好' : '我好' }}</p>

  <!-- v-html 指令可以渲染html片段在所绑定的html元素的innerhtml中 -->
  <p v-html="text"></p>

  <!-- 双括号中可以函数调用,函数return的结果会解析在双括号中 -->
  <p>{{ func(new Date().toDateString()) }}</p>

  <!-- 动态绑定的属性,如果值为null或者undefined 那么该属性将会被移除 -->
  <div v-bind:style="styleObj">今天是个好日子</div>
  <!-- 动态属性简写 -->
  <div :style="styleObj">今天是个好日子</div>
  <div :class="className">今天是个好日子</div>
  <div :id="idName">今天是个好日子</div>

  <!-- 布尔型的属性 -->
  <!-- 需要注意:属性值是布尔类型属性,只有在属性值为false的时候,该属性才不会生效 -->
  <!-- 需要注意:属性值是布尔类型属性,属性值为空字符串("")或者true的时候,该属性会生效 -->
  <button :disabled="isButtonDisabled">Button</button>

  <!-- 动态绑定多个值 -->
  <!-- attr 是一个对象 对象的key被当作是属性 对象的value被当作是属性值 -->
  <div v-bind="attr">明天也是好日子</div>

  <!-- 动态绑定的属性中也可以是一个简单的js表达式 -->
  <div :style="true ? 'color:purple' : ''">后天也是好日子</div>

  <!-- 
    总结:双括号的模板插值语法,与动态绑定的属性中都可以使用一些简单的js表达式,包括函数调用
   -->
   
  <!-- 
    指令的一些特殊用法:
      attrname 是指令的动态参数
      attrVal  是动态参数的值
   -->
  <a :[attrName]="attrVal">百度一下</a>
  <button @[eventName]="onClick">点一下</button>
  
</template>

<!-- 下面这句 使用的是 vue3.2 的 组合式api的语法糖 -->
<script lang="ts" setup>
const myname = 'zrs'

const text = '<h2>今天是个好日子</h2>'

const styleObj = {
  color: 'red'
}

const className = 'color'

const idName = 'color'

const isButtonDisabled = true

const attr = {
  class: 'box',
  id: 'box'
}
const func = (str: string) => {
  return str + ' 是个好日子'
}

const attrName = ref('href')
const attrVal = ref('http://www.baidu.com')

const eventName = ref('click')

const onClick = () => {
  alert('触发了事件')
}
</script>

<style>
body {
  background-color: #1a1a1a;
  color: #fff;
}

.color {
  color: green;
}

#color {
  color: yellow;
}

.box {
  height: 100px;
  width: 100px;
  background-color: aqua;
}

#box {
  color: green;
}
</style>