Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

javascript - Vue component doesn't reload with getter data (not reactive)

I have this ecommerce mock app in Vue and Vuex. This page shows a list of phones and there is a filter which filters phones based on the phone brands through checkboxes.

The problem is the page doesn't refresh straight away after I click the checkbox to filter. If I click another page and click back to the original page, then the page gets filtered.

enter image description here

The is my source code. Some code is removed for brevity.

Product.vue

import { mapActions } from "vuex";
import BrandFilter from "../components/BrandFilter";

export default {
  data() {
    return {
      products: this.$store.getters.filterProducts
    };
  },
  components: { BrandFilter }
};
<template>
  <div class="container">
    <div class="row">
      <div class="col-lg-3"><BrandFilter></BrandFilter></div>
      <div class="col-lg-9">
        <div class="row">
          <div v-for="product in products" :key="product.id">            
                <h4 class="card-title product__title">
                  {{ product.title }}
                </h4>                            
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you set a data item to a getter in Product.vue, it gets assigned only once. If the getter changes, the data doesn't change with it:

data() {
  return {
    products: this.$store.getters.filterProducts  // ? Incorrect
  }
}

Use a computed instead with mapGetters to keep the component data synced with the Vuex data:

import { mapGetters } from 'vuex';
computed: {
  ...mapGetters(['filterProducts'])  // ? Correct
}

Change your template to use that computed:

<div v-for="product in filterProducts" :key="product.id">            
   <h4 class="card-title product__title">
      {{ product.title }}
   </h4>                            
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...