<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的字符串值
function String(){[native code]}
Vue组件中的prop首字母显示正确的字符串值,但位置已分配了功能 我在做什么错了?
答案 0 :(得分:0)
Vue初始化组件时,data
函数无法访问视图模型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>
答案 1 :(得分:0)
经过大量分析,我发现了导致这种现象的问题。
<practicesearch-component @findlocation="getlocation" :initial=postalTown" />
上面的postalTown最初不是在Vue实例中设置的,而是在安装时进行安装的,因此该组件正在传递未初始化的字符串对象,而不是postalTown的初始化值
我在postalTown上添加了:key属性,如下所示,该属性导致组件使用postalTown的初始值重新渲染 也许这不是最好的选择,但它可行
<practicesearch-component @findlocation="getlocation" :key=postalTown :initial=postalTown ></practicesearch-component>