【问题标题】:How to set data in child component from computed prop如何从计算的道具中设置子组件中的数据
【发布时间】:2021-02-12 13:56:36
【问题描述】:

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

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

为了更好的可读性,我会删掉大部分代码。

父组件(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>

子组件(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>

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

【问题讨论】:

    标签: javascript vue.js nuxt.js vuex vue-multiselect


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 2021-02-20
      • 2019-06-07
      相关资源
      最近更新 更多