Automatically assigning a default dynamic value to a dropdown option using Vue.js

I need to set a default selected value for the select option element, but I am facing difficulty in achieving the desired result.

<template>
    <select v-model="tutor_work.start_year">
      <option>{{tutor_work.start_year}}</option>
      <option v-for="year in years" :key="year" :value="year">{{ year }}</option>
    </select>
<template/>
<script>
import axios from 'axios'
export default {
    data() {
        return {
            tutor_work: {
                organization: "",
                start_year: "",
                finish_year: "",
            },
        }        
    },
    mounted() {
        this.getUserData()
    },
    methods: {
        async getUserData() {
            await axios
                .get('api/v1/user/tutor/work/')
                .then(response =>{
                    this.tutor_work = response.data
                })
                .catch(error => {
                    console.log(error)
                })
        }
    },
    computed : {
        years () {
        const year = new Date().getFullYear()
        return Array.from({length: year - 1980}, (value, index) => 1981 + index)
        }
  }
}
</script>

The functionality of the code is correct, but the issue lies with the positioning of the selected value. The selected year (e.g., start_year: 2019) is displayed as the first option instead of being placed after the previous year, such as 2018.

Answer №1

To assign the value of

:selected="tutor_work.start_year"
to a select element:

new Vue({
  el: "#demo",
    data() {
        return {
            tutor_work: {
                organization: "ff",
                start_year: "2010",
                finish_year: "2019",
            },
        }        
    },
    computed : {
      years () {
        const year = new Date().getFullYear()
        return Array.from({length: year - 1980}, (value, index) => 1981 + index)
      }
  }
}
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
    <select v-model="tutor_work.start_year">
      <option v-for="year in years" :key="year" :value="year" :selected="tutor_work.start_year">{{ year }}</option>
    </select>
</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

How can I trigger an onclick event for a link automatically upon loading in Laravel?

I am presenting the link below: <a href="javascript:void(0)" onclick="xtenderSearchItem.modal_visibility = ! xtenderSearchItem.modal_visibility;">Request</a> My goal is for it to change the language of the page (which occu ...

Issue with webcomponents-lite.js file

Encountering this particular error message in the console while attempting to run the application: webcomponents-lite.js:64Uncaught TypeError: Cannot read property 'getAttribute' of null at webcomponents-lite.js:64 at Object.549 (webcomp ...

Can someone help me troubleshoot this issue with my code so that my website can open in a blank page using about:blank?

I'm currently facing an issue while trying to make one of the pages on my website open with an about:blank URL upon loading. Despite embedding the code in my index.html file, it doesn't seem to be functioning properly. Here's the code I&apos ...

Is there a way to incorporate an 'input' type within an Icon Button component from Material UI in a React project?

Kindly review my code below. I have revamped it for clarity so you won't need to stress about important details! const test = () => { return ( <label > <input type='file' multiple style={{ display: &ap ...

What is the best way to eliminate the input range in a React date range picker?

Here is an image illustrating a date range picker: https://i.stack.imgur.com/pwKaI.png I am looking to remove the labels for days before today and starting from today in the date range picker. How can I achieve this? Below is my code snippet: class Better ...

What are some ways to customize the appearance of VueJS components?

I am new to Vue, so I apologize if this question seems silly or if I have overlooked something. I believed that you could target a custom element like this: my-element { styles go here} However, when I created an element, it appears that I can only targe ...

`Proliferating values through constantly changing addition`

I am facing an issue with my code that involves 3 input fields: <div class="row"> <input onblur="calc_basic_amount();" id="rate_basic"></input> <input onblur="calc_basic_amount();" id="qty_b ...

What are the steps to retrieve historical stock data for over one year using Yahoo Finance YQL query?

I am currently using a Tableau web connector to retrieve stock price data. Here is the source code: <html> <meta http-equiv="Cache-Control" content="no-store" /> <head> <title>Stock Quote Connector-Tutorial</title> <sc ...

Display new information within a div element seamlessly without refreshing the page

Just a heads-up, I'm new to HTML development... Currently working on a website using Bootstrap. There are some buttons on the left side shown in the screenshot, and my goal is to update the content on the right without having to reload the entire pag ...

Updating the DOM with an EventListener in Angular 5 is not functioning properly

Situation : Utilizing an Angular PWA for communication with an iOS native app via WKWebview. Implementing messageHandlers to facilitate data sharing between TypeScript and Swift logic code. Issue : Employing addEventListener to monitor a specific event on ...

Utilizing SVG elements for interactive tooltips

Can the < use > element show the rect tooltip on mouseover in modern browsers? Refer to 15.2.1 The hint element. <svg id="schematic" version="1.2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <symbol i ...

Clicking on an item will now automatically remove it from the selection, rather than requiring you to click on a specific

Is there a way to customize the design of select2 items in a multi-select box so that users can easily remove selected items by clicking anywhere on the button, rather than just the small "cross" icon on the left-hand side? Refer to the image; instead of n ...

Learn how to customize button styles in ExtJS with the pressedCls configuration option

Is there a way to change the color when a button is pressed? I tried using the pressedCls config but it didn't work. How can I fix this issue or is there another method to set the CSS when a button is pressed? Thank you so much! Javascript: Ext.crea ...

My VW controller is receiving null from AJAX

Hey there, I've been dealing with this issue for a few hours now and still haven't found a solution. All my request data looks good except for subscriptionTag, as it always comes back as null when the request is sent to the server. I even tried ...

How to set the element in the render method in Backbone?

Currently, I am in the process of developing a web page utilizing BackboneJS. The structure of the HTML page consists of two divs acting as columns where each item is supposed to be displayed in either the first or second column. However, I am facing an is ...

Are you experiencing issues with the .submit() function when used in conjunction with other

Currently, I am working on a survey form that incorporates JQuery to dynamically display or hide fields based on user selections. //FORM CONDITIONALS: This script is responsible for hiding all the helpfulness radios and only displaying them when "Yes" fo ...

Make sure to validate a form when submitting from an external source rather than through an HTML

In my form, there are various input fields (some acting as inputs even if they're not). Each field is validated upon submission by angular validation and html attributes like required, ng-maxlength, minlength, etc. Now, we want to implement a keyboar ...

The Vue.js DevTools panel is mysteriously absent from the developer tools interface

I've been struggling to get the vue development tools panel to show up. Despite trying multiple solutions such as deleting and reinstalling the extension, hard refreshing, reopening the tools, adding Vue.config.devtools = true;, and various combinati ...

Utilizing Angular 2's offline capabilities for loading locally stored JSON files in a project folder

I've been attempting to load a local JSON file from my Angular 2 project folder using the HTTP GET method. Here is an example of the code snippet: private _productURL = 'api/products/products.json'; getProducts(): Observable<any> ...

Utilizing Angular for enhanced search functionality by sending multiple query parameters

I'm currently facing an issue with setting up a search functionality for the data obtained from an API. The data is being displayed in an Angular Material table, and I have 8 different inputs that serve as filters. Is there a way to add one or more s ...