Vue コンポーネントでは、マウントされたフェーズで非同期データをリクエストする関数が呼び出されましたが、返された結果は data の値に割り当てられましたが失敗しました。割り当て後、console.log() には明らかに値がありましたが、ページには値がありませんでした。更新されました。私はいつもそれが nuxt ライフサイクルの理由だと思っていましたが、明らかにそうではありません。この問題はたまにしか発生しないため、ページのすべてのレンダリングでこの問題が発生するわけではありません。
1. シンプルで失礼な方法: ページ全体をリロードします (不親切なエクスペリエンスなので、お勧めしません)
2. 悪い方法: v-if を使用する
<template>
<my-component v-if="showComponent" />
</template>
<script>
export default {
data() {
return {
showComponent: true,
};
},
methods: {
forceRerender() {
// 从 DOM 中删除 my-component 组件
this.showComponent = false;
this.$nextTick(() => {
// 在 DOM 中添加 my-component 组件
this.showComponent = true;
});
}
}
};
</script>
3. より良い方法: Vue の組み込みの ForceUpdate メソッドを使用します。
Vueインスタンスを強制的に再レンダリングします。すべてのサブコンポーネントではなく、インスタンス自体とスロット コンテンツに挿入されたサブコンポーネントにのみ影響することに注意してください。
// 全局
import Vue from 'vue';
Vue.forceUpdate();
// 使用组件实例
export default {
methods: {
methodThatForcesUpdate() {
// ...
this.$forceUpdate();
// ...
}
}
}
4. 最良の方法: コンポーネントに重要な変更を加える
<template>
<component-render :key="componentKey" />
</template>
export default {
data() {
return {
componentKey: 0,
};
},
methods: {
forceRerender() {
this.componentKey += 1;
}
}
}
5. Object.assign() を使用する
MDN: Object.assign() メソッドは、すべての列挙可能なプロパティの値を1 つ以上のソース オブジェクトからターゲット オブジェクトにコピーするために使用されます。ターゲットオブジェクトを返します。
方法:
オブジェクトのクローンを作成するには、Object.assign({}, target)
配列のクローンを作成するには、Object.assign([], target) で
上記の例の add メソッドを変更します。
this.queryParam = Object.assign({}, this.queryParam);
6. Vue.set( target , key , value) を使用します。
方法:
target: 変更するデータ ソース (オブジェクトまたは配列にすることができます)
key 変更する特定のデータ。配列要素の変更の場合、key はインデックスを表し、オブジェクトの場合、key は
キー値の再割り当てされた値 を表します。
add() {
this.$set(this.persons, 1, {key: 'newkey', name: '888'})
console.log(this.persons)
}
7. ... 展開構文
オブジェクト データ obj、obj = {...obj}を使用します。
配列 arr の場合は、arr = [...arr]を使用します。
add() {
this.persons[1] = {key: 'newkey', name: '888'}
this.persons = [...this.persons]
console.log(this.persons)
}