【问题标题】:Setting default dynamic value for <select> option in Vue js在 Vue js 中为 <select> 选项设置默认动态值
【发布时间】:2022-01-03 16:50:49
【问题描述】:

我想为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 年之后推出。

【问题讨论】:

    标签: javascript vue.js vuejs3


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2014-11-27
      • 2018-11-12
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 2020-06-28
      • 2021-05-25
      • 2022-11-29
      • 2019-09-18
      相关资源
      最近更新 更多