LoginSignup
0
0

More than 3 years have passed since last update.

【Nuxt.js】v-bindを使ってclassを動的なものにする (入力欄にカーソルがfocusした時だけ指定のcssを適用させる)

Posted at

概要

入力欄にカーソルがfocusした時だけ指定のcssを適用させたかったので、v-bindディレクティブ(下記は省略記法)を使って、classを動的なのものにした

実際のコード

<template>
  <div :class="{ 'input_box': true, 'shadow_input_box': active }">
    // 省略
    <input type="text" @focus="onFocus" @blur="onBlur" />
  </div>
</template>
  • 'input_box': trueとした場合、input_box classに適用されているstyleが常に適用される (falseにすれば適用されなくなる)
<style>
.input_box {
  // 常に適用したいプロパティ: ; を記載
}
</style>
  • shadow_input_box classには以下のCSSを指定
<style>
.shadow_input_box {
  box-shadow: 0px 0px 3px grey;
}
</style>
  • 入力欄にカーソルがあたった時のみシャドウつけたい(上記のCSSを適用させたい)ので、scriptは次のようになる
<script>
export default {
  data() {
    return {
      active: false  // 初期値
    }
  },
  methods: {
    onFocus() {
      this.active = true  // シャドウがつく
    },
    onBlur() {
      this.active = false  // シャドウはつかない
    }
  }
}
</script>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0