Vue ref 更改不会在更新后将更改应用到组件

问题描述 投票:0回答:1

我有一个用vue3实现的表单。该表单由三个文本输入和一个复选框组组成。

我正在使用 bootstrap-vue 表单,它是复选框组。

我调用 api 在表单上设置默认值,在 api 响应后,我像下面的代码一样更新引用,并且所有三个文本输入都得到了很好的更新

问题出在复选框组组件上。 选中的项目不会被选中,尽管它们位于 tagList 引用内部。

// I set the formValues ref and api call to get default values in this composable.
// taglist will be a list of strings: tagList = ['example']
  const formValues = ref<IArticleFormValues>({
    title: '',
    body: '',
    description: '',
    tagList: [],
  });

  const { data, isFetching } = useQuery({
    queryKey: ['fetchArticleBySlug', slug],
    queryFn: () => fetchSingleArticleService(slug)
  });

  watch(data, () => {
    if (data.value?.article) {
      formValues.value = {
        ...data.value.article,
        tagList: data.value.article.tagList.map((item) => item),
      };
    }
  });

// I then inject this data using vue inject like this
provide(formInjectionKey, {  formValues });

这是复选框组组件。标签只是这种格式的另一个选项列表。

tags =  [{text:'example',value:'example'}] 

tagList 也会是这样的。

tagList = ['example']

<script setup lang="ts">
import CustomCheckboxGroup from '@/components/DesignSystem/components/CustomCheckboxGroup.vue';
import { inject } from 'vue';

const { formValues } = inject(formInjectionKey);

</script>

<template>
<CustomCheckboxGroup v-else :options="tags" v-model="formValues.tagList" />
</template>

这是 CustomCheckboxGroup 组件。

// CustomCheckboxGroup.vue
<script setup lang="ts">
defineProps<{ value?: any[]; options: any[] }>();
</script>

<template>
  <b-form-group>
    <b-form-checkbox-group
      :value="value"
      @input="$emit('input', $event)"
      :options="options"
      v-bind="$attrs"
      stacked
    ></b-form-checkbox-group>
  </b-form-group>
</template>

javascript vue.js vuejs3 bootstrap-vue
1个回答
0
投票

复选框输入使用不同的属性来设置其选中值。 使用

:checked="value"
代替
:value="value"

© www.soinside.com 2019 - 2024. All rights reserved.