zoukankan      html  css  js  c++  java
  • vue中select的使用以及select设置默认选中

    简介

    今天写pc端引入vue,遇到了一个问题,就是我循环出select内的数据以后,发现原本默认显示第一条的select框变成了空白,要选择后才有显示,结果查了好多文档,讲的都不是很清楚,后来看到一句提示,试了一下发现居然还有这种隐藏属性。所以,我决定自己写下来,讲清楚。

    解决过程

    html代码如下,通过v-model可以获取到选中的值,如果option中存在value属性,优先获取value值即coupon.id,如果不存在,则获取option的文本内容,也就是下面代码中coupon.name.

    <select name="public-choice" v-model="couponSelected" @change="getCouponSelected">                                        
        <option :value="coupon.id" v-for="coupon in couponList" >{{coupon.name}}</option>                                    
    </select>

    首先说明,html这样写没有任何问题,动态的select的正确使用方法就是这样。

    下面是js代码:

            var vm = new Vue({
                    el: '#app',
                    data:{
                        couponList:[
                            {
                                id: 'A',
                                name: '优惠券1'
                            },
                            {
                                id: '1',
                                name: '优惠券2'
                            },
                            {
                                id: '2',
                                name: '优惠券3'
                            }
                        ],
                        couponSelected: '',
                    },
                    created(){
                //
    如果没有这句代码,select中初始化会是空白的,默认选中就无法实现 this.couponSelected = this.couponList[0].id; }, methods:{
                getCouponSelected(){
                            //获取选中的优惠券
                            console.log(this.couponSelected)
                        }
    
                    }
                })

    上面的js代码是正确的,我下面说明一下隐藏属性是什么

    隐藏属性就是

    当我们把v-model中的couponSelected,也就是data里的couponSelected的值赋值为循环的option中的value后,那这个option就会被默认选中

    小结

    这篇文章其实主要是说select默认选中的问题,select使用以及数据获取只是顺带说明,vue关于表单元素的使用,如单选,复选可以参考官方文档,现在的官方文档其实已经写得很不错了,放链接https://cn.vuejs.org/v2/guide/forms.html,感兴趣的话可以看一下,试一下。

  • 相关阅读:
    faster with MyISAM tables than with InnoDB or NDB tables
    w-BIG TABLE 1-toSMALLtable @-toMEMORY
    Indexing and Hashing
    MEMORY Storage Engine MEMORY Tables TEMPORARY TABLE max_heap_table_size
    controlling the variance of request response times and not just worrying about maximizing queries per second
    Variance
    Population Mean
    12.162s 1805.867s
    situations where MyISAM will be faster than InnoDB
    1920.154s 0.309s 30817
  • 原文地址:https://www.cnblogs.com/till-the-end/p/8473738.html
Copyright © 2011-2022 走看看