Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

105
Vistas
Setting default dynamic value for <select> option in Vue js

I wanted to set default selected value for select option element but cannot get proper 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 code works fine, but the problem is selected value (which is year) is on the first raw not after previous year, for example in the option there are years and start_year: 2019 is from server and it's on the first option, not coming after 2018.

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can bind :selected="tutor_work.start_year" :

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>

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos