Updating a Vue ref does not result in the component reflecting the changes made

My Vue3 form has three text inputs and a group of checkboxes. To implement this, I am using the bootstrap-vue form along with its checkbox-group component.

After calling an API to fetch default values for the form, I update the ref as shown below. Interestingly, the text inputs all get updated correctly.

However, I encountered an issue with the checkbox group component. Even though the checked items are present in the tagList ref, they do not get checked.

// In this composable, I set the formValues ref and make an API call to retrieve default values.
// 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),
      };
    }
  });

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

Let's take a look at the checkbox-group component. The 'tags' variable represents a list of options formatted like this:

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

The 'tagList' will be structured similarly to this:

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>

Lastly, here is the code for the CustomCheckboxGroup component:

// 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>

Answer №1

To establish the checked value for checkbox inputs, utilize a distinct property. Replace :value="value" with :checked="value"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for displaying a Rails action without a layout in html format using Ajax

Is it possible to render the new action without the application layout and without altering the current code structure? class FoobarController < ApplicationController def new @foobar = Foobar.new end # ... end When a user clicks on = link_ ...

Tips for utilizing useQuery in React JS class component:

Currently, I'm working on an app that is exclusively built using React JS class components. Since UseQuery only functions with function components and the Query tag has been deprecated, I'm facing some challenges in getting the data I need. Any s ...

A method designed to accept an acronym as an argument and output the corresponding full name text

Having trouble with my current task - I've got an HTML file and external JS file, and I need a function that takes an element from the 'cities' array as input and returns a string to be used in populating a table. I've set up a functio ...

Learn how to incorporate additional rows into a table by pressing the plus button within the table with the help of Angular

I require some assistance. I am looking to dynamically generate a row after clicking on the plus button using angular.js. The newly created row should contain an ID and model generated dynamically. Here is an overview of my code: <table class="table ta ...

Tips on activating the CSS style while typing using the onChange event in React

Is it possible to dynamically adjust the width of an input as we type in React? Currently, my input has a default width of 1ch. I would like it to increase or decrease based on the number of characters entered, so that the percentage sign stays at the end ...

Activate JavaScript functions by pressing the enter key, allowing for various searches, AJAX requests, and DataTable displays to occur seamlessly without the need to refresh

I recently developed a web page that integrates an AWS API interface to interact with an RDS Aurora MySQL Serverless database. Users can input a SQL statement and click the Query button, which triggers an AJAX request, returns JSON data, and converts the d ...

How can a child value be transferred from a client component to a parent component on the server side?

I am facing a situation where a client-side component needs to send a value to its parent component which is server-side. I have tried using useState and other hooks, but so far it has been unsuccessful. Can anyone provide guidance on how to achieve this? ...

Divide the sentence using unique symbols to break it into individual words, while also maintaining

Is there a way to split a sentence with special characters into words while keeping the spaces? For example: "la sílaba tónica es la penúltima".split(...regex...) to: ["la ", "sílaba ", "tónica ", "es ", "la ", "penúltima"] ↑ ...

Discovering methods to store browser credentials securely in jQuery

I need to prevent the login button from being enabled when either the username or password fields are empty. Check out the code snippet below: $(document).ready(function(){ $('input').on('keyup blur mouseenter', function(e) { ...

What is the best way to conceal the dt tag when the dd tag contains no value

Is there a way to hide the "Subject" if the "subject_title" field is empty? <dt class="col-sm-6 text-dark" >Subject</dt> <dd class="col-sm-6">{{$course_dtl->subject_title }}</dd> For example, I would li ...

What is the best way to insert fresh input values into a different element?

click here to view image description I am working with an input element where I take input values and store them in an element. However, I would like to know how to input new values into the next element. Any assistance would be greatly appreciated. Thank ...

Implementing append operations in JavaScript without relying on the id attribute

Is there a way to specify the second div without assigning it an ID or using any attributes, and then perform an append operation inside it? For instance, indicating that the p element should be appended within the second div without relying on an ID or ...

Is it possible to use reactjs and react-router to showcase either a component or {this.props.children}?

Here's the scene: I have multiple components where certain words can be clicked to link to a reference page/component. If the highlighted words are not clicked, the component is displayed as is (and there are many of them with this feature and a menu ...

Enhancing User Experience with Load Indicator during State Changes in React Native

I'm facing an issue where the page for displaying a single item is loading slowly - I need to delay the page from loading until the object has changed. After checking the navigation params through console log, I can see that the id changes when each b ...

Ways to display a price near a whole number without using decimal points

Currently, I am working on an ecommerce project where the regular price of an item is $549. With a discount of 12.96% applied, the sale price comes down to $477.8496. However, I want the sale price to be displayed as either $477 or $478 for simplicity. Yo ...

What is the best way to invert the positioning of the li elements to move upwards?

https://i.stack.imgur.com/mZaoS.png Seeking assistance on adjusting the height of bars to start from the bottom and go upwards instead of starting from the top position and going downwards. The JavaScript code below is used to generate the li elements and ...

Trouble with shadow rendering in imported obj through Three.js

After importing an object from blender and setting every mesh to cast and receive shadows, I noticed that the rendered shadows are incorrect. Even after merging the meshes thinking it would solve the issue, the problem persisted. It seems like using side: ...

Revolutionizing messaging with Vue JS and Firebase

My web application is designed to check if a user has messages in the Firebase database. If messages are found, it retrieves the data from the users who sent those messages from my local database and displays them in a list using a v-for loop. The display ...

Automatic page switch upon dropdown selection

I'm not very proficient in JavaScript and I want to modify a form so that it automatically updates when a dropdown option is selected, without needing to click a separate "Go" button. How can I adjust the code below? It contains three different dropd ...

The lite-server is unable to find an override file named `bs-config.json` or `bs-config.js`

I've been working on running my first Angular 2 app. I carefully followed the steps provided by angular2. However, upon running the command npm start, I encountered the following error in the terminal: No bs-config.json or bs-config.js override fil ...