簡體   English   中英

Vue.js 中父數據發生變化時如何重新渲染內部組件

[英]How to re-render inner component when data from parent changes in Vue.js

當某個值在父組件中更新時,我試圖從 API 獲取一些數據,然后在子組件中使用它。 我嘗試了幾件事,但都沒有用。

這是我的組件的簡化版本:

家長

<template lang="html">
<div id="wrapper">
    <h4>My Super Component</h4>
    <button v-on:click="setListID">Load another list</button>
    <ChildComponent :usernames="usernames"></ChildComponent>
</div>
</template>

<script>
import ChildComponent from "./ChildComponent.vue"

export default {
    components: {
        ChildComponent
    },
    data() {
        return {
            listID: 0,
            usernames: undefined,
        }
    },
    watch: {
        listID: function(newID) {
            this.usernames = getUsernames(newID)
        }
    },
    methods: {
        setListID() {
            let id = +prompt("Input the list ID");
            if (Number.isNaN(id)) {
                alert("Please input a valid number");
            } else {
                this.listID = id;
            }
        }
    },
    async mounted() {
        this.usernames = await getUsernames(this.listID)
    }
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// Simulating an API call
async function getUsernames(listID) {
    sleep(200).then(() => {
        switch (listID) {
            case 0:
                return ['Pierre', 'Paul', 'Jaques']
            case 1:
                return ['Riri', 'Fifi', 'Loulou']
            case 2:
                return ['Alex', 'Sam', 'Clover']
            default:
                return []
        }
    })
}
</script>

孩子

<template lang="html">
    <p v-for="username in usernames">{{username}}</p>
</template>

<script>
export default {
    props: {
        usernames: Object
    },
}
</script>

我在孩子身上得到的道具是 Promise,我試圖傳遞一個數組,但由於獲取數據的 function 是異步的,我不能等待手表,我有點卡住了。

更新:

我認為問題來自這段代碼:

// Simulating an API call
async function getUsernames(listID) {
    await sleep(200).then(() => {
        switch (listID) {
            case 0:
                return ['Pierre', 'Paul', 'Jaques']
            case 1:
                return ['Riri', 'Fifi', 'Loulou']
            case 2:
                return ['Alex', 'Sam', 'Clover']
            default:
                return []
        }
    })
    return 'returned too early'
}

function 總是返回'returned too early' 當我刪除此默認返回值時,將返回undefined並且我的子組件將其用作數組。

嘗試像下面的片段

 Vue.component('Child', { template: ` <div class=""> <p v-for="username in usernames">{{username}}</p> </div> `, props: { usernames: Array }, }) new Vue({ el: '#demo', data() { return { listID: 0, usernames: undefined, } }, watch: { listID: async function(newID) { this.usernames = await this.getUsernames(newID) } }, methods: { setListID() { let id = +prompt("Input the list ID"); if (Number.isNaN(id)) { alert("Please input a valid number"); } else { this.listID = Number(id); } }, sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }, getUsernames(listID) { return this.sleep(200).then(() => { switch (listID) { case 0: return ['Pierre', 'Paul', 'Jaques'] case 1: return ['Riri', 'Fifi', 'Loulou'] case 2: return ['Alex', 'Sam', 'Clover'] default: return [] } }) } }, async mounted() { this.usernames = await this.getUsernames(this.listID) } }) Vue.config.productionTip = false Vue.config.devtools = false
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="demo"> <div id="wrapper"> <h4>My Super Component</h4> <button v-on:click="setListID">Load another list</button> <Child:usernames="usernames"></ChildComponent> </div> </div>

您發送數組的道具似乎有問題,但在您期望 object 的子組件中。試試下面的代碼看看

<template lang="HTML">
  <p v-for="(username, index) in usernames" :key="index">{{username}}</p>

</template>

<script>
export default {
    props: {
        type: Object, // or Aarray
        default: () => {
          return {} // [] if the type is array
        }
    },
}
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM