在 Vue js 中为 <select> 选项设置默认动态值

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

我想为 select 选项元素设置默认选择值,但无法获得正确的结果

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

代码工作正常,但问题是选择的值(年份)是在第一个原始数据上而不是在前一年之后,例如在选项中有年份并且 start_year: 2019 来自服务器并且它是第一个选项,2018 年之后不会出现。

您可以绑定 :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>