0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

vueがリアクティブにならない場合

Last updated at Posted at 2021-12-04

これは結構ハマりやすそう

エラー例

配列の中身を表示するシンプルなプログラム
ボタンをクリックすると配列の2番目が「青 → 緑」に変更する

<template>
  <div>
    <button @click="fun">ボタン</button>
    <div v-for="(data, index) in datas" :key="index">
      {{data}}
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return{
      datas:["","","",]
    }
  },

  methods:{
    fun(){
      this.datas[1]=""
      console.log(this.datas)
    }
  }
};
</script>

が動かない。

コンソールを見ると配列は

['赤', '緑', '黄']

ちゃんと変わっている。

正しい例

公式ドキュメントを見ると(配列に関してのところ)この書き方では、変更を検知できないらしい。

色々やり方はあると思うが一例として[set]を使ってみる。

<template>
  <div>
    <button @click="fun">ボタン</button>
    <div v-for="(data, index) in datas" :key="index">
      {{data}}
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return{
      datas:["","","",]
    }
  },

  methods:{
    fun(){
      this.$set(this.datas, 1, "");
      console.log(this.datas)
    }
  }
};
</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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?