Vue.jsにおける動的クラスバインディングと状態管理手法

動的クラスバインディング

条件に基づくクラスの動的適用:

<div :class="isCollapsed ? 'form-control active' : 'form-control'"></div>
<div :class="dynamicClass"> // dynamicClass = "status-active highlight"
<div :class="{'selected': sortOrder === 'asc'}"></div>

監視プロパティと算出プロパティの比較

監視プロパティ(watch):

  • 事前にdataで定義必須
  • 非同期処理可能(setTimeout等)
  • 簡略化記法はデータ変更不要時のみ

算出プロパティ(computed):

  • data内で定義不可
  • 同期的処理のみ(非同期不可)
  • 常に値を返す必要あり

実装例

<template>
  <div>
    <p>結合メッセージ: {{combinedText}}</p>
    <p>反転メッセージ: {{reversedText}}</p>
    <button @click="updateData">データ更新</button>
    <ul>
      <li v-for="user in users">{{user.id}} - {{user.score}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      textA: '初めまして',
      textB: 'Vue.js',
      config: {
        id: 1001,
        mode: 'standard'
      },
      users: [
        {id: 'user01', score: 85},
        {id: 'user02', score: 92}
      ]
    }
  },
  watch: {
    config: {
      deep: true,
      handler(current) {
        console.log('設定変更:', current);
      }
    },
    textA(newVal, oldVal) {
      console.log('テキスト更新:', newVal, oldVal);
    }
  },
  computed: {
    reversedText() {
      return this.textA.split('').reverse().join('');
    },
    combinedText: {
      get() {
        return `${this.textA} ${this.textB}`;
      },
      set(value) {
        return value;
      }
    }
  },
  methods: {
    updateData() {
      this.config.id++;
      this.textA = '変更後';
      this.users[1].score += 5;
    }
  }
}
</script>

ルーター操作

非コンポーネント環境でのナビゲーション:

import router from '@/router';
router.push({ path: '/auth' });

DOM更新制御

this.$nextTick(() => {
  const selected = _.pick(this.template, 'title', 'createDate', 'modifyDate');
  this.form.setFieldsValue(selected);
});

コンポーネントプロパティ検証

props: {
  width: Number,
  settings: {
    type: Object,
    default: () => ({})
  },
  level: {
    type: Number,
    required: true,
    validator: v => v >= 1
  }
}

ナビゲーションイベント

<router-link 
  @click.native="trackNavigation(route)"
>
  {{route.title}}
</router-link>

複数行テンプレートリテラル

const message = `複数行の
テキストを
表示`;

動的コンポーネント

<keep-alive>
  <component :is="currentComponent"></component>
</keep-alive>
<button @click="toggleComponent">切替</button>

ライフサイクルフック

beforeDestroy/destroyed: ルート閉鎖時に発火(v-if/v-show切替では非発火)

タグ: vue.js クラスバインディング ウォッチャ 算出プロパティ Vueルーター

7月6日 19:47 投稿