防止不必要的VUE组件重新读取

发布于 2025-01-31 08:29:31 字数 1649 浏览 0 评论 0原文

由于不需要的恢复,我在多选择组件中失去了状态。我的数据是这样构成的:

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

每个表单值在模板中生成多选择性,但是如果我添加一个新值(例如this.form.push({key:this.form.form.length,value,value:null});),模板中的每个多选择均已启用。内部状态的这种不必要的变化导致选择框上失去视觉反馈。

我已经尝试设置:键以防止重读者,但这尚未起作用。有什么建议吗?

多选择组件为 vueform/multiselect 。这是一个jsfiddle,显示了行为: htttps://jsfiddle.net/libertie/libertie/libertie/sey/sey1t4mb/34mb/31

内联示例:

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>

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文