LoginSignup
9
6

More than 3 years have passed since last update.

【Vue.js】Observerから配列の値を取得する

Last updated at Posted at 2020-06-05

はじめに

帰ってくる配列の値が{__ob__: observer}になってundefinedになった方が対象です。
Vue.jsを勉強し始めて、一ヶ月ほどなので正しい方法だと保証はできませんですが、動かすための一つの方法として見守ってほしいです。

環境

・node 12.7.0
・vue-cli 4.3.1

ソースコード

  import firebase from 'firebase/app';
  import'firebase/database'
  import Vue from 'vue';

  created(){
    this.database = firebase.database();
    this.todosRef = this.database.ref('todos');
    var that = this;
    this.todosRef.on('child_added', function(snapshot){
      that.todos.push(snapshot.val());
    });
    this.todosRef.on('child_removed', function(snapshot){
      //削除された要素が除かれた配列を新しく生成する
      let newTodos = that.todos.filter(function(value) {
        //valueとsnapshot.val()の値が異なるものだけを返す。
        return JSON.stringify(value) !== JSON.stringify(snapshot.val());
      })
      //新しい配列をthat.todosに代入する
      that.todos = newTodos;
    });
  },
  data() {
    return {
      todos: []
    }
  }

困ったこと

filter関数内でvalueとsnapshot.val()の値が異なるものだけ返そうとした時、

  let newTodos = that.todos.filter(function(value) {
    //valueとsnapshot.val()の値が異なるものだけを返す。
    return value!== snapshot.val();
  })

valueの値が{__ob: observer}となっており、返り値がundefinedになってしまう。
(console.log(value)で確認してみると{
ob__: observer}が吐き出されます。)

改善策

JSON.stringifyでvalueとsnapshot.val()の値をJSON形式に変換して判定する。

  let newTodos = that.todos.filter(function(value) {
    //valueとsnapshot.val()の値が異なるものだけを返す。
    return JSON.stringify(value) !== JSON.stringify(snapshot.val());
  })

あとは{__ob__: observer}だけが邪魔でした。
配列の中身を取り出せればよかったのでJSON.stringify()を使いました。

おわりに

正しい解決方法といえるかわかりません。
でも{__ob__: observer}から中身を取り出してとりあえず開発を進めたいという方にはオススメできます。

9
6
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
9
6