如何从computed prop中设置子组件中的数据



我目前正在用vue-multiselect构建一个过滤器。一切工作,但我面临的唯一问题是,在页面重新加载,标签(v-model)是空的。

原因肯定是,v-modelselectedOption在页面重新加载为空,因为来自父组件的prop是一个计算属性。

为了最好的可读性,我将删去大部分代码。

父组件(productlist . value):

<template>
<section>
<ProductListFilter v-bind:currentProductType="currentProductType"
</section>
</template>
<script>
import {mapGetters} from 'vuex';
export default {
computed: {
...mapGetters({
currentProductType: 'shop/productTypes/currentProductType',
}),
},
mounted() {
this.$store.dispatch('shop/productTypes/setCurrentProductType', this.productType);
},
}
</script>

子组件(productlistfilter . value)

<template>
<div>
<div v-if="allProductTypes && currentProductType" class="col-4">
<multiselect v-model="selectedProductType"
:options="options"
:multiple="false"
:close-on-select="true"
label="title"
placeholder="Produkttyp"
:allowEmpty="false">
</multiselect>
</div>
</template>
<script>
import Multiselect from 'vue-multiselect'
export default {
name: "ProductTypeFilter",
props: ['currentProductType'],
components: { Multiselect },
data() {
return {
selectedProductType: this.currentProductType,
}
},  
}
</script>

现在的问题是,如果我在我的模板中打印{{ selectedProductType }},当然它是空的,因为在父组件中,属性是一个计算属性,来自api。我已经尝试在mount中使用this.selectedProductType = this.currentProductType,但这也不起作用,

您可以添加watch属性,以便在currentProductType更改时更新selectedProductType。在子组件中:

watch: {
currentProductType(val) {
this.selectedProductType = val;
}
}

最新更新