繁体   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