gpt4 book ai didi

javascript - prop 更新时更新 VueJS 组件数据属性

转载 作者:搜寻专家 更新时间:2023-10-30 22:22:02 25 4
gpt4 key购买 nike

我正在构建一个 VueJS 组件,它需要在更新 prop 时更新数据属性,但是它没有像我预期的那样工作。

基本上,流程是某人通过我拥有的自动完成组件搜索联系人,如果匹配,则会向父组件发送事件。

该联系人将属于一个组织,我将数据向下传递到更新数据属性的组织组件。但是它没有更新它们。

传递给组织组件的 Prop 已更新(通过事件),但数据属性 values 未显示此更改。

这是我的组件结构的图示...

enter image description here

这是我的代码...

父组件

    <template>
<div>
<blink-contact
:contact="contact"
v-on:contactSelected="setContact">
</blink-contact>

<blink-organisation
:organisation="organisation"
v-on:organisationSelected="setOrganisation">
</blink-organisation>
</div>
</template>

<script>
import BlinkContact from './BlinkContact.vue'
import BlinkOrganisation from './BlinkOrganisation.vue'

export default {
components: {BlinkContact, BlinkOrganisation},

props: [
'contact_id', 'contact_name', 'contact_tel', 'contact_email',
'organisation_id', 'organisation_name'
],

data () {
return {
contact: {
id: this.contact_id,
name: this.contact_name,
tel: this.contact_tel,
email: this.contact_email
},

organisation: {
id: this.organisation_id,
name: this.organisation_name
}
}
},

methods: {
setContact (contact) {
this.contact = contact
this.setOrganisation(contact.organisation)
},

setOrganisation (organisation) {
this.organisation = organisation
}
}
}
</script>

子组件(眨眼组织)

        <template>
<blink-org-search
field-name="organisation_id"
:values="values"
endpoint="/api/v1/blink/organisations"
:format="format"
:query="getQuery"
v-on:itemSelected="setItem">
</blink-org-search>
</template>

<script>
export default {
props: ['organisation'],

data() {
return {
values: {
id: this.organisation.id,
search: this.organisation.name
},
format: function (items) {
for (let item of items.results) {
item.display = item.name
item.resultsDisplay = item.name
}
return items.results
}
}
},

methods: {
setItem (item) {
this.$emit('organisationSelected', item)
}
}
}
</script>

如何在 prop 更改时更新子组件的数据属性?

谢谢!

最佳答案

使用 watch .

watch: {
organisation(newValue){
this.values.id = newValue.id
this.values.search = newValue.name
}
}

但是,在这种情况下,您似乎可以只使用计算属性而不是数据属性,因为您所做的只是将值传递给搜索组件。

computed:{
values(){
return {
id: this.organisation.id
search: this.organisation.name
}
}
}

关于javascript - prop 更新时更新 VueJS 组件数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44570949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com