1. ホーム
  2. javascript

[解決済み] vuejsでコンポーネントの初期データをリセットする適切な方法はありますか?

2022-09-05 05:25:03

質問

特定の開始データのセットを持つコンポーネントがあります。

data: function (){
    return {
        modalBodyDisplay: 'getUserInput', // possible values: 'getUserInput', 'confirmGeocodedValue'
        submitButtonText: 'Lookup', // possible values 'Lookup', 'Yes'
        addressToConfirm: null,
        bestViewedByTheseBounds: null,
        location:{
            name: null,
            address: null,
            position: null
        }
}

これはモーダルウィンドウ用のデータで、表示されたときにこのデータで始まるようにしたい。ユーザーがウィンドウからキャンセルした場合は、すべてのデータをこのデータにリセットしたい。

データをリセットするメソッドを作成し、手動ですべてのデータプロパティを元の状態に戻すことができることは知っています。

reset: function (){
    this.modalBodyDisplay = 'getUserInput';
    this.submitButtonText = 'Lookup';
    this.addressToConfirm = null;
    this.bestViewedByTheseBounds = null;
    this.location = {
        name: null,
        address: null,
        position: null
    };
}

しかし、これは本当にずさんだと思います。つまり、もし私がコンポーネントのデータプロパティを変更したら、リセットメソッドの構造を更新することを忘れないようにする必要があるということです。これは小さなモジュール式のコンポーネントなので、絶対にひどいというわけではありませんが、私の脳の最適化部分が悲鳴を上げることになります。

私がうまくいくと思った解決策は、初期データプロパティを ready メソッドで初期データのプロパティを取得し、保存されたデータを使用してコンポーネントをリセットすることです。

data: function (){
    return {
        modalBodyDisplay: 'getUserInput', 
        submitButtonText: 'Lookup', 
        addressToConfirm: null,
        bestViewedByTheseBounds: null,
        location:{
            name: null,
            address: null,
            position: null
        },
        // new property for holding the initial component configuration
        initialDataConfiguration: null
    }
},
ready: function (){
    // grabbing this here so that we can reset the data when we close the window.
    this.initialDataConfiguration = this.$data;
},
methods:{
    resetWindow: function (){
        // set the data for the component back to the original configuration
        this.$data = this.initialDataConfiguration;
    }
}

しかし initialDataConfiguration オブジェクトはデータとともに変化しています (これは理にかなっています。なぜなら読み込みメソッドでは initialDataConfiguration はデータ関数のスコープを取得しているからです。

スコープを継承せずに初期設定データを取得する方法はないでしょうか?

私が考えすぎていて、もっと良い/簡単な方法があるのでしょうか?

初期データをハードコーディングすることが唯一の選択肢でしょうか?

どのように解決するのですか?

  1. 初期データをコンポーネント外の関数に抽出する
  2. その関数を使用して、コンポーネントに初期データを設定します。
  3. 必要なときに状態をリセットするためにその関数を再利用する。

// outside of the component:
function initialState (){
  return {
    modalBodyDisplay: 'getUserInput', 
    submitButtonText: 'Lookup', 
    addressToConfirm: null,
    bestViewedByTheseBounds: null,
    location:{
      name: null,
      address: null,
      position: null
    }
  }
}

//inside of the component:
data: function (){
    return initialState();
} 


methods:{
    resetWindow: function (){
        Object.assign(this.$data, initialState());
    }
}