簡體   English   中英

為Vue組件中的數據分配prop值

[英]Assigning a prop value to data in a Vue Component

<template>
    <div class="container p-2">
        <form id="Lookup">
            <div class="row p-2">
                <div class="col-12 input-group ">
                    <input type="text" name="postcode"   :placeholder="initial" v-model="location" class="form-control p-3"><div class="input-group-append"><i class="material-icons input-group-text" @click="$emit('findlocation', location)">location_searching</i></div>
                </div>
            </div>
        </form>
    </div>
</template>

<script>
    export default{
        props: ['initial'],
        data: function () {
            return {
              location : this.initial
            }
        }
    }
</script>

上面是我的Vue組件,該組件傳遞了一個名為initial的字符串值。該值從下面的模板傳遞

<practicesearch-component @findlocation="getlocation" :initial=postalTown" />

其中postalTown是主Vue的數據屬性

但是我沒有在位置中獲取postalTown的字符串值,而是

函數String(){[本地代碼]}

Vue組件中的prop縮寫顯示正確的字符串值,但是位置已分配了功能我在做什么錯?

當Vue初始化您的組件時, data功能無權訪問View Model this 您可以使用安裝的掛鈎分配值

export default {
    props: ['initial'],
    data: () => ({
        location: undefined
    }),
    mounted() {
        this.location = this.initial;
    }
}

請注意 ,以這種方式,無論何時父級中的initial更改, location都不會更新

這是一個快速示例:

 Vue.productionTip = false; Vue.component('child', { template: ` <div class="child"> Child component: <br/> location: {{ location }} <br/> initial: {{ initial }} </div> `, props: { initial: String }, data: () => ({ location: undefined }), mounted () { this.location = this.initial; } }); new Vue({ el: '#app', template: ` <div class="parent"> Parent Component <br/> location: {{ location }} <child :initial="location" /> </div> `, data: () => ({ location: 'US' }) }); 
 .parent { background-color: darkgray; padding: 1em; border: solid 1px black; color: white; } .child { background-color: gray; padding: 1em; border: solid 1px black; color: white; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"></div> 

經過大量分析,我發現了導致這種現象的問題。

<practicesearch-component @findlocation="getlocation" :initial=postalTown" />

上面的postalTown最初不是在Vue實例中設置的,而是在掛載中設置的,因此該組件正在傳遞未初始化的字符串對象,而不是postalTown的初始化值

我在postalTown上添加了:key屬性,如下所示,該屬性導致組件以postalTown的初始值重新渲染。也許這不是最佳選擇,但它可以工作

<practicesearch-component @findlocation="getlocation" :key=postalTown :initial=postalTown ></practicesearch-component>

暫無
暫無

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

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