0
点赞
收藏
分享

微信扫一扫

8. vue3中类的操作方式

有点d伤 2022-03-23 阅读 30
vue.js
<script setup>
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
import HelloWorld from './components/HelloWorld.vue'
</script>

<template>
  <!--类class-->

  <div>
  <!--第一种写法,放置字符串-->
  <h1 :class="msg">hello</h1>
  <!--第二种写法,放置对象. active:是对象属性  isActive: 是变量-->
  <!--下面的作用是控制这个类是否生效-->
  <h1 :class="{active:isActive}">hello2</h1>
  <button @click="toggleActive">切换active</button>
  <!--第三种写法,放置数组-->
  <!--<h1 :class="['swiper','active']">hello3</h1>-->
  <h1 :class=arr>hello3</h1>
  <!--第四种写法,数组和对象结合-->
  <h1 :class="[classname4,{active:isActive}]">hello4</h1>
  </div>
</template>

<script>
//命令式
//document.querySelector("h1").innerHTML="helloworld"
//声明式, 先声明出变量。
export default{
  name:'App',
  data(){
    return{
      msg:"helloworld",
      isActive:true,
      arr:['swiper','active'],
      classname4:"abc"
    }
  },
  methods:{
    toggleActive(){
      this.isActive= !this.isActive,
      //测试点击后删除数组最后一个元素
      this.arr.pop()
      this.classname4="cba"
    }
  }
}
</script>

<style>
/* 表示类名 */
.active{
  background: yellowgreen;
}
</style>
<template>
  <!--style-->
  <!--第一种写法,放置字符串,背景色变成了黄色-->
  <div>
  <h1 :style="msg">hello</h1>
  <!--第二种写法,放置对象. {}表示里面是对象。background:是对象属性  purple: 是变量值-->
  <!--下面的作用是控制这个类是否生效-->
  <h1 :style="{background:'purple'}">hello2</h1>
   <!--如果有多个属性-->
  <h1 :style="styleObj">hello3</h1>
  <!--第四种写法,数组和对象的结合-->
  <h1 :style="[styleObj,{width:'500px'}]">hello4</h1>
  <!--切换样式-->
  <button @click="toggleActive">切换active</button>
  </div>
</template>

<script>
//命令式
//document.querySelector("h1").innerHTML="helloworld"
//声明式, 先声明出变量。
export default{
  name:'App',
  data(){
    return{
      msg:"background:yellow;",
      isActive:true,
      arr:['swiper','active'],
      classname4:"abc",
      styleObj:{
        // 如果遇到多个单词组合可使用引号 'background-color'
        // 也可使用驼峰的命名
        background : 'pink',
        border:'1px solid blue',
        boxSizing:"border-box"
      }
    }
  },
  methods:{
    toggleActive(){
      this.styleObj.backgroundColor = "skyblue"
    }
  }
}
</script>

<style>
/* 表示类名 */
.active{
  background: yellowgreen;
}
</style>
举报

相关推荐

0 条评论