简体   繁体   English

如何从计算的道具中设置子组件中的数据

[英]How to set data in child component from computed prop

I am currently building a filter with vue-multiselect .我目前正在使用vue-multiselect构建过滤器。 Everything works, but the only problem I am facing is, that on page reload, the label (v-model) is empty.一切正常,但我面临的唯一问题是,在页面重新加载时,label(v-model)是空的。

The reason surely is, that the v-model selectedOption is on page reload empty, because the prop from the parent component is a computed property.原因肯定是,v-model selectedOption在页面重新加载时为空,因为来自父组件的 prop 是计算属性。

For the best readability I will cut most of the code.为了获得最佳可读性,我将删除大部分代码。

Parent component (ProductList.vue):父组件(ProductList.vue):

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

Child component (ProductListFilter.vue)子组件(ProductListFilter.vue)

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

Now the problem is, that if I print {{ selectedProductType }} in my template, of course it is empty because in the parent component, the property is a computed property, coming from an api.现在的问题是,如果我在模板中打印{{ selectedProductType }} ,它当然是空的,因为在父组件中,该属性是一个计算属性,来自 api。 I already tried to use this.selectedProductType = this.currentProductType in mounted but this does not work too,我已经尝试在安装中使用this.selectedProductType = this.currentProductType但这也不起作用,

You could add a watch property to update selectedProductType whenever currentProductType changes.您可以添加一个watch属性以在currentProductType更改时更新selectedProductType In your child component:在您的子组件中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM