<template>
  <div class="container">
    <h1 class="title">Vue 样式示例</h1>
    <p class="content">这是一个带有样式的 Vue 组件。</p>
    <button class="btn" @click="changeColor">点击改变颜色</button>
  </div>
</template>
<script>
export default {
  name: 'StyleExample',
  data() {
    return {
      isRed: false
    };
  },
  methods: {
    changeColor() {
      this.isRed = !this.isRed;
    }
  }
};
</script>
<style scoped>
.container {
  padding: 20px;
}
.title {
  color: blue;
}
.content {
  font-size: 16px;
  color: gray;
}
.btn {
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border: none;
  cursor: pointer;
}
/* 使用动态类 */
.red {
  color: red;
}
.green {
  color: green;
}
</style>模板部分 (<template>):
@click 事件,点击时会调用 changeColor 方法。脚本部分 (<script>):
StyleExample。data 中定义了一个布尔值 isRed,用于控制文本颜色的切换。methods 中定义了 changeColor 方法,每次点击按钮时切换 isRed 的值。样式部分 (<style scoped>):
scoped 属性,确保样式仅应用于当前组件。.container、.title、.content 和 .btn。.red 和 .green,用于根据 isRed 的值动态改变颜色。动态类:
v-bind:class 或简写的 :class 来动态绑定类名,例如:<h1 :class="{ red: isRed, green: !isRed }">Vue 样式示例</h1>这样就实现了一个简单的 Vue 组件,并且展示了如何在 Vue 中应用和动态切换样式。
上一篇:vue3 ref调用子组件方法
下一篇:vue cli service
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站