vue中select的使用以及select设置默认选中20190222

1.问题:

写角色页面,就是我循环出select内的数据以后,发现原本默认显示第一条的select框变成了空白

2.解决思路:

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

3.大神的Demo参考:

<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就会被默认选中

4.小结

官方参考文档:https://cn.vuejs.org/v2/guide/forms.html

以上demo参考链接:https://www.cnblogs.com/till-the-end/p/8473738.html 

5.实际尝试操作:

遇到的问题,第一次赋值可以,然后打开第二行信息的收应该是空,实际是admin,

怀疑是赋值问题,打开时默认赋值时是空的,然后再查询一次后赋值,或者是直接当前角色信息,空为空,值为值。

 

<template>
  <div>
    <!--添加按钮-->
    <el-row style="padding: 10px 0;">
      <el-col :span="20" :offset="2">
        <el-button type="info" @click="handleAdd()">添加用户</el-button>
      </el-col>
    </el-row>

    <!--列表展示部分-->
    <el-row style="padding: 10px 0;">
      <el-col :span="20" :offset="2">
        <el-table
          :data="dataList"
          border
          v-loading.body="isTableLoading"
          style="width: 100%">

          <el-table-column
            label="用户名字">
            <template scope="scope">
              <span style="margin-left: 10px">{{ scope.row.name }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="邮箱">
            <template scope="scope">
              <span style="margin-left: 10px">{{ scope.row.email }}</span>
            </template>
          </el-table-column>
          
          <el-table-column
            label="状态" width="100px">
            <template scope="scope">
              <span style="margin-left: 10px">
                <el-tag v-if=" scope.row.status == 0 " type="warning">未激活</el-tag>
                <el-tag v-if=" scope.row.status == 1 " type="success">正常</el-tag>
                <el-tag v-if=" scope.row.status == 2 " type="danger">冻结</el-tag>
              </span>
            </template>
          </el-table-column>

          <el-table-column
            label="上次登陆时间">
            <template scope="scope">
              <span v-if="scope.row.lastLoginTime" style="margin-left: 10px">{{ scope.row.lastLoginTime | TimeFormat }}</span>
            </template>
          </el-table-column>

          <el-table-column  label="操作" width="400px;">

            <template scope="scope">
              <el-button
                v-if="scope.row.status == 1"
                size="small"
                type="danger"
                @click="handleFreeze(scope.row.id, 2, scope.$index)">冻结
              </el-button>

              <el-button
                v-if="scope.row.status == 2"
                size="small"
                type="success"
                @click="handleFreeze(scope.row.id, 1, scope.$index)">解冻
              </el-button>

              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row.id, scope.$index)">删除
              </el-button>

              <el-button
                size="small"
                type="warning"
                @click="handleModify(scope.row)">修改
              </el-button>

              <el-button
                size="small"
                type="warning"
                @click="shandleModify(scope.row)">查看
              </el-button>

              <el-button
                size="small"
                type="warning"
                @click="setRole(scope.row.id,scope.row.roleId,scope.row.role_name)">设置角色
              </el-button>

            </template>

          </el-table-column>

        </el-table>

      </el-col>

    </el-row>

    <!--分页-->
    <el-row>
      <el-col :span="24" style="text-align:center">
        <el-pagination
          style="text-align:center;margin-top:20px"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount">
        </el-pagination>
      </el-col>
    </el-row>

    <!--增加和修改模块部分-->
    <el-dialog :title="title" :visible.sync="addUserVisible" size="tiny">
      <el-form :model="inviteForm" :rules="inviteRules" ref="inviteForm">
        <el-form-item label="用户名字" :label-width="formLabelWidth" prop="name">
          <el-input v-model="inviteForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="inviteForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户电话" :label-width="formLabelWidth" prop="telephone">
          <el-input v-model="inviteForm.telephone" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleInviteUser()" :loading="isInviting">确 定</el-button>
      </div>
    </el-dialog>

    <!--查看部分-->
    <el-dialog :title="title" :visible.sync="addUserVisible1" size="tiny">
      <el-form :model="inviteForm1" :ref="inviteForm1">
        <el-form-item label="用户名字" :label-width="formLabelWidth" prop="name">
          <span style="margin-left: 10px">{{inviteForm1.name}}</span>
        </el-form-item>
        <el-form-item label="用户邮箱" :label-width="formLabelWidth" prop="email">
          <span style="margin-left: 10px">{{inviteForm1.email}}</span>
        </el-form-item>
        <el-form-item label="用户电话" :label-width="formLabelWidth" prop="telephone">
          <span style="margin-left: 10px">{{inviteForm1.telephone}}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserVisible1 = false">确 定</el-button>
      </div>
    </el-dialog>

    <!--设置角色-->
    <el-dialog :title="title" :visible.sync="addUserVisible2" size="tiny">
      <el-form :model="inviteForm2" :ref="inviteForm2">
        <div style="display:none;">{{inviteForm2.id}}</div>
        <select name="public-choice" v-model ="roleSelected" style="width: 200px;" autocomplete="off" @change ="changeRole($event)">
          <option value="" >请选择</option>
          <option :value="role.id"  v-for="role in roleList"  >
            {{ role.role_name }}
          </option>
        </select>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button  @click="saveRole()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { mapActions } from 'vuex'

  export default {

    data(){
      //校验邮箱
      const emailValidator = (rule, value, callback)=>{
        if((/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i.test(value))){
          callback()
        }else{
          callback(new Error('请输入正确的邮箱地址'))
        }
      }

      return {
        isInviting:false,//增加页面和修改页面
        addUserVisible:false,//增加和修改页面
        addUserVisible1:false,//查看页面
        addUserVisible2:false,//角色选择页面
        isTableLoading:false,//列表加载
        title:'',//所有弹出层的共用title
        currentUserInfo:null,//当前用户信息
        roleSelected:'',//设置select选中
        option:'',
        inviteForm:{//增加和修改页面的字段信息
          name:"",
          email:"",
          telephone:""
        },
        inviteForm1:{//查看页面的字段信息
          name:"",
          email:"",
          telephone:""
        },
        inviteForm2:{//角色选择页面的字段信息
          id:"",//当前选中用户的id
          roleId:"",//当前用户选中的角色的id
        },
        formLabelWidth:"80px",//设置宽度
        dataList:[],//列表加载的集合
        roleList: [],//角色选择的集合
        pageSize: 10,//分页信息-每页多少
        totalCount:0,//分页信息-总共多少页
        pageNum:1,//第几页
        inviteRules:{//增加或修改页面的校验规则
          name: [
            { required: true, message: '请输入用户名字', trigger: 'blur' }
          ],
          email: [
            { required: true, validator: emailValidator, trigger: 'blur' }
          ],
        }
      }

    },

    //初始化加载并获取用户列表(ok)
    mounted: function () {
      this.isTableLoading = true;
      this.getUserList({
        pageSize: this.pageSize,
        pageNum: this.pageNum
      }).then((result) => {
        this.isTableLoading = false;
        this.totalCount = result.totalCount;
        this.dataList = result.resultData;
        console.log(this.dataList);
      }, () => {
        this.isTableLoading = false;
        this.$message.error('列表加载失败!');
      })
    },

    methods:{

      ...mapActions([
        'getUserList',
        'updateUser',
        'deleteUser',
        'inviteUser',
        'getUserById',
        'getRoleList',
        'getRoleInfo',
      ]),

      //点击增加用户的按钮(ok)
      handleAdd(){
        this.addUserVisible = true,
          this.title = '增加用户',
          this.inviteForm = { name:"", email:"",telephone:"" };
        this.currentUserInfo = null
      },

      //修改用户的按钮(ok)
      handleModify(data){
        this.title = '修改用户';
        this.addUserVisible = true;
        this.currentUserInfo = data;
        this.getUserById({
          id: data.id
        })
          .then((result) => {
            this.inviteForm = {
              name:data.name,
              email:data.email,
              telephone:data.telephone
            }
          }, () => {})
      },

      //查看按钮(ok)
      shandleModify(data){
        this.title = '查看用户';
        this.addUserVisible1 = true;
        this.getUserById({
          id: data.id
        })
          .then((result) => {
            this.inviteForm1 = {
              name:data.name,
              email:data.email,
              telephone:data.telephone
            }
          }, () => {})
      },

      //执行增加或者修改(ok)
      handleInviteUser(){
        this.$refs['inviteForm'].validate((valid) => {
          if (valid) {
            this.isInviting = true;
            this.isTableLoading = true;
            (()=>{
              if(this.currentUserInfo){
                this.inviteForm.id = this.currentUserInfo.id;
                return this.updateUser(this.inviteForm)
              }else{
                return this.inviteUser(this.inviteForm)
              }
            })()
              .then(()=>{
                this.isInviting = false;
                this.addUserVisible = false;
                this.inviteForm = { name:"", email:"",telephone:"" };
                this.$message({
                  message: this.title+'成功',
                  type: 'success'
                });
                this.isTableLoading = true;
                this.getUserList({
                  pageSize:this.pageSize,
                  pageNum:this.pageNum
                }).then((result) => {
                  this.isTableLoading = false;
                  this.totalCount = result.totalCount;
                  this.dataList = result.resultData;
                }, () => {
                  this.isTableLoading = false;
                  this.$message.error('列表加载失败!');
                })
              },()=>{
                this.isInviting = false;
                this.$message({
                  message: this.title+'失败',
                  type: 'error'
                });
              })
          }
        })
      },

      //删除用户(ok)
      handleDelete(userId, index) {
        this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.isTableLoading = true;
          this.deleteUser({
            id: userId
          })
            .then(() => {
              this.getUserList({
                pageSize: this.pageSize,
                pageNum: this.pageNum
              })
                .then((result) => {
                  this.isTableLoading = false;
                  this.totalCount = result.totalCount;
                  this.dataList = result.resultData;
                  this.$message({
                    type: 'success',
                    message: '删除成功!'
                  });
                }, () => {
                  this.isTableLoading = false;
                  this.$message.error('列表刷新失败!');
                })
            }, () => {
              this.$message({
                type: 'error',
                message: '删除失败!'
              });
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      //冻结或者解冻用户
      handleFreeze(userId, status, index){
        this.isTableLoading = true;
        this.updateUser({
          id:userId,
          status:status
        })
          .then((result) => {
            this.isTableLoading = false;
            this.dataList[index].status = status;
            this.$message({
              message: '修改成功!',
              type: 'success'
            });
          }, () => {
            this.isTableLoading = false;
            this.$message.error('修改失败!');
          })
      },

      //获取用户的所有角色的按钮(ok)
      setRole(id,roleId,role_name){
        //调用方法获取角色列表
        this.user_id = id;//获取角色id
        this.addUserVisible2 = true;
        this.title = '选择角色';
        this.getRoleList({//调用方法获取所有角色的列表
        })
          .then((result) => {
            this.isTableLoading = false;
            this.roleList = result.resultData;
            //console.log("当前角色列表"+this.roleList);
            //如果没有这句代码,select中初始化会是空白的,默认选中就无法实现
            //this.roleSelected = this.roleList[0].id;
            //console.log("当前选中角色id:"+this.roleSelected);
            this.roleSelected = roleId;//设置默认选中的值
          }, () => {
            this.isTableLoading = false;
            this.$message.error('列表加载失败!');
          })
      },

      //获取每次option选中时的id(ok)
      changeRole(event) {
        this.option = event.target.value; //获取ID,即option对应的ID值
        console.log("变更后的角色"+this.option);
      },

      //增加用户的角色(ok)
      saveRole(){
        this.addUserVisible2 = false;
        //调用方法给角色赋值
        //alert(this.option);
        this.inviteForm2 = { id:this.user_id, roleId:this.option};
        this.updateUser(this.inviteForm2)
      },

      //分页
      handleSizeChange(pageSize){
        this.pageSize = pageSize;
        this.pageNum = 1;
        this.isTableLoading = true;
        this.getUserList({
          pageSize:this.pageSize,
          pageNum:this.pageNum
        })
          .then((result) => {
            this.isTableLoading = false;
            this.totalCount = result.totalCount;
            this.dataList = result.resultData;
          }, () => {
            this.isTableLoading = false;
            this.$message.error('列表加载失败!');
          })
      },

      //分页
      handleCurrentChange(pageNum){
        this.pageNum = pageNum;
        this.isTableLoading = true;
        this.getUserList({
          pageSize:this.pageSize,
          pageNum:this.pageNum
        })
          .then((result) => {
            this.isTableLoading = false;
            this.totalCount = result.totalCount;
            this.dataList = result.resultData;
          }, () => {
            this.isTableLoading = false;
            this.$message.error('列表加载失败!');
          })
      },


      //修改角色的按钮

    }



  }

</script>

<style lang="less" scoped>

</style>

 

  • 6
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值