Configuring the default value for a selection menu in Vue3

Obtaining all available categories:

const fetchCategories = async () => {
  let response = await axios.get(`/api/get_all_category/`)
  categories.value = response.data.categories
}

The structure of categories.value is shown here:

https://i.sstatic.net/IIXai.png

Initializing the default option:

let selectedCategory
const fetchSingleProduct = async () => {
  let response = await axios.get(`/api/get_edit_product/${props.id}`)
  form.value = response.data.product
   
  //form.value.category_id ranges from 1 to 6
  selectedCategory = ref(form.value.category_id) 
}

Constructing the select dropdown menu:

<div class="my-3">
  <p>Select product type</p>
  <select v-model="selectedCategory">
    <option v-for="category in categories" :key="category.id" :value="category.id">
      {{ category.name }}
    </option>
  </select>
</div>

All options are displayed correctly, but the default selection does not seem to be applied as expected.

Answer №1

Consider setting selectedCategory as a reactive variable using ref:

const { ref, computed } = Vue
const app = Vue.createApp({
  setup() {
    const categories = ref([{id: 1, name: 'aaa'}, {id: 2, name: 'bbb'}, {id: 3, name: 'ccc'}])
    let selectedCategory = ref(null)
    const getSingleProduct = () => {
      //let response = await axios.get(`/api/get_edit_product/${props.id}`)
     // form.value = response.data.product
      //form.value.category_id is a number from 1 to 6
       selectedCategory.value = 3
    }
    getSingleProduct()
    return { categories, selectedCategory }
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div class="my-3">
    <p>Select product category:</p>
    <select v-model="selectedCategory">
      <option v-for="category in categories" :key="category.id" :value="category.id" :selected="selectedCategory">
        {{ category.name }}
      </option>
    </select>
  </div>
</div>

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

The simple passport.js sign-up feature is not successful as it mistakenly believes that the username is already in

Currently, I am working on setting up a basic signup feature for my Node + Express + Sequelize application using passport.js. The database is empty at the moment, and I am utilizing the passport-local strategy to extract the user's email and password ...

Ways to retrieve the initial value and proceed with a subsequent subscription method

I have created a basic angular 7 web application with Firebase database integration. In my code, I am attempting to store the initial list in an array using the subscribe method and then display that array using console.log(). However, there seems to be a ...

Sending an Array from JavaScript to Asp.net Core

Below is the javascript code that invokes the asp.net CustomHeatMapDate function $('.Date').change(function () { var data = []; console.log(); var dateList = [{"Date":"03/23/2016"}, {"Date":"03/24/2016"}]; $.ajax({ async: ...

Save a randomly generated string in the Session, which will be replaced when accessed through a different PHP file

I have created a form with a hidden input field, and its value is dynamically set using a function. <?php class Token { public static function generate(){ return $_SESSION['token'] = base64_encode(openssl_random_pseudo ...

What is the process for obtaining a JSON file in AngularJS upon clicking a button?

Starting off with AngularJS and feeling excited. I have successfully created a form with two input boxes. Just below the input boxes, I have added: <input ng-model="id.todoList" type="text" name="input" placeholder="Enter tasks here"> <input ng ...

"Converting a basic function into a promise for an AngularJS tutorial: How to handle the error message '

To help my colleagues understand AngularJS, I am creating a dummy exercise. In this example, I want to call a service that provides an Object Array to be passed into a Controller and assigned to a $scope variable (using information about the Beatles). Inst ...

Utilize the same Apollo GraphQL query definition across various Vue components for different properties

On my vue screen, I am trying to utilize a single apollo graphql query that I have defined for two different properties. From what I understand, the property name must correspond with an attribute name in the returned json structure. I attempted to use the ...

Query key array failing to update when key is modified

Encountering an issue with the query key array not updating when the selected warehouse ID is changed. This causes useQuery to use outdated data instead of fetching new data for the updated warehouse ID. Struggling to figure out how to update the query k ...

Which one relies on the other: angular-data or angular-cache?

I'm struggling to get angular-cache set up properly. According to the documentation: Angular-cache is a dependency of angular-data and must be loaded before angular-data if you are using angular-data. That's all well and good, but what if I only ...

When the LI element is clicked, it triggers the display of another LI element without affecting the rest of the

New to the web development scene and trying to figure out how to create a collapsible text feature using HTML, JavaScript, and JQuery. I've got the styling down but struggling with the scripting part. Here's an example of what I'm trying to ...

Frames of Animation

Seeking assistance in understanding how to create frame animation using JavaScript or CSS. Attempting to replicate the animation seen on this website. Intrigued by the road animation and unsure if it is achieved using a plugin or just JavaScript and CSS. ...

JavaScript generating HTML code causing malfunctions

I have been attempting to implement the IN Place Editing feature using JQuery. Below is the code snippet editinplace.js $(document).ready(function() { //When div.edit me is clicked, run this function $("div.editme").click(function() { // ...

Exploring the concept of Promises through the lens of recursion

I am dealing with a MongoDB collection that looks like this [ { "classId": "1", "name": "Input", "definition": [ { "property": [ { "classId": "12", "name": "One" }, { ...

What is the best method for securely storing and managing refresh and access tokens within a node.js application?

Currently, I am working with next.js and I am looking for a way to persist an API refresh token without using a database in my application. What would be the recommended practice for storing this token securely so that it can be updated as needed? Storin ...

The issue of page content failing to refresh when loaded using AJAX technology

My script utilizes AJAX to dynamically load specific pages on a website. These pages display information that updates based on the current time. However, I have encountered an issue where the page content remains static when loaded through AJAX, almost as ...

The component "SafeAreaViewRN" could not be located within the UIManager

Upon attempting to open a bundle on my Android device, I encountered the following error message: A warning was displayed stating that the app was accessing a hidden field in android's view accessibility delegate. Additionally, an Invariant Violati ...

Troubleshooting issue with Highcharts 3D rendering after using setState()

When working on implementing a 3d pie chart in React using react highchart, I encountered an issue. Whenever I utilize this.setState() inside the lifecycle method componentDidMount(), the 3d chart shifts from its original position to the right diagonally. ...

There is no throttleTime function available in Angular 6 within Rx Js

Currently, my Angular 6 project is utilizing angular/cli": "~6.1.5 and rxjs": "^6.0.0. As a newcomer to Angular 6, I decided to dive into the official documentation to enhance my understanding. Here's a reference link I found useful: http://reactivex ...

Attempting to create an array using jQuery's :checked selector

In my table structure below, I have multiple rows with various data: <tr class="row"> <td class="row-checkbox-delete-row"> <input tabindex="-1" class="checkbox-delete-row" type="checkbox" /> </td> <td class="r ...

Unlock the power of React Testing Library with the elusive waitFor function

I came across an interesting tutorial about testing React applications. The tutorial showcases a simple component designed to demonstrate testing asynchronous actions: import React from 'react' const TestAsync = () => { const [counter, setC ...