簡體   English   中英

將數據從HTTP請求傳遞到子組件VueJS

[英]Passing data from HTTP request to a Sub-component VueJS

我的VueJS (Vue 2)應用程序遇到了一些問題。

我有一個登錄組件,該組件有一個名為“錯誤”的子組件,它只是一個引導警報,顯示應來自后端(通過HTTP請求)的消息,問題是我不太清楚如何處理HTTP請求后動態填充此消息。

因此,重申一下,我有一個父級Login組件,該組件顯示一個Login表單,該組件在Template中需要一個“ Error”子組件,這只是一個引導警報。

我需要根據“登錄”組件發出的HTTP請求的響應為該子組件設置一條消息,這是“錯誤”組件的直接父級,我希望消息顯示在...上。

你通過道具做到這一點嗎? 如果是這樣,究竟如何? 這是我當前用於Login組件的HTML模板

<template>
    <div class="container-fluid">
        <!-- Error display component -->
        <error v-if="hasError" v-bind:errorMessage='errorMessage'></error>
        ...Login form HTML....
</template>

<script>
    import Error from './partials/Error.vue';

    export default {
        mounted() {
            this.usernameInput  = document.getElementById('email')
            this.passwordInput  = document.getElementById('password')
            this.submitButton   = document.getElementById('submitBtn')
            this.errorContainer = document.getElementById('errorContainer') 
        },
        methods: {
            submitForm: (e) => {
                e.preventDefault();

            }
        },
        data() {
            return {
                usernameInput: undefined,
                passwordInput: undefined,
                submitButton: undefined,
                errorContainer: undefined,
                errorMessage: null,
                hasError: false,
                email: null,
                password: null
            }
        },
        components: {
            'error': Error
        }
    }   
</script>

對於錯誤組件

<template>
    <div class="alert alert-danger fade in">
    <a href="#" class="close" data-dismiss="alert">&times;</a>
    <strong>Error!</strong> {{ errorMessage }}
    </div>
</template>

<script>
    export default {
        props: ['']
    }
</script>

更新

適應您的代碼:

methods: {
  submitForm(e) { // dont use fat arrow to not loose context
    e.preventDefault();

    if (some_error) {
      this.hasError = true;
      this.errorMessage = 'Please fix ....';
    }
  }
}

錯誤組件:

export default {
    props: ['errorMessage']
}

您將執行以下操作:

Vue.component('login', {
  template: '<div>...</div>',
  data() {
    return { message: '' };
  },
  methods: {
    request() {
      // make a request and then set this.message
    }
  }
})

Vue.component('error', {
  template: '<div>{{ message }}</div>',
  props: ['message']
})

就像喬納塔斯·沃克(Jonatas Walker)在他的帖子中所說的那樣,它可以正常工作,您應該在父登錄組件上具有錯誤消息的data變量,然后應將其傳遞給子組件,如下所示

<error v-if="hasError" :errorMessage='errorMessage'></error>

:errorMessage='errorMessage'表示我將'errorMessage'數據屬性作為道具v綁定到子對象中,該道具也稱為'errorMessage'

然后,在子組件的Javascript部分中,我可以說

    props: ['errorMessage']

然后,我可以在該組件中使用errorMessage,就像它是在該組件中定義的常規數據屬性一樣。

{{ errorMessage }}

例如將工作正常。

暫無
暫無

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

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