Prevent Unwanted Rerendering of Vue Component

Viewed 62

I am losing state in a multiselect component due to unwanted rerendering. My data is structured like this:

form: [
  { key: 0, value: null },
  { key: 1, value: null },
  ...
]

Each form value generates a multiselect in my template, but if I add a new value (e.g. this.form.push({ key: this.form.length, value: null });), every multiselect in the template is rerendered. This unwanted change of internal state results in the loss of visual feedback on the select boxes.

I've tried setting :key to prevent rerenders, but that hasn't worked. Any recommendations?

The multiselect component is vueform/multiselect. Here is a jsfiddle that shows the behavior: https://jsfiddle.net/libertie/sey1t4mb/31

Inline Example:

const app = Vue.createApp({
  data: () => ({
    form: [
        { key: 0, value: null }
    ]
  }),

  methods: {
    add() {
        this.form.push({ key: this.form.length, value: null });
    },
    async fetchRecords(query) {
      const response = await axios.get(API_URL)
      .then(response => {
        if (Array.isArray(response.data.results)) {
          return response.data.results;
        }
        return [];
      });
      
      return await response;
    }
  }
});
<div v-for="field in form" :key="field.key">
  <Multiselect
    v-model="field.value"
    :filter-results="false"
    :options="async (query) => await fetchRecords(query)"
    searchable
  />
</div>

<button
  @click="add"
  type="button"
>Add field</button>
0 Answers
Related