vue中select的使用以及select設置默認選中


vue中select的使用以及select設置默認選中
https://blog.csdn.net/weixin_36810906/article/details/87877753

1.問題:

寫角色頁面,就是我循環出select內的數據以后,發現原本默認顯示第一條的select框變成了空白

2.解決思路:

html代碼如下,通過v-model可以獲取到選中的值,如果option中存在value屬性,優先獲取value值即coupon.id,如果不存在,則獲取option的文本內容,也就是下面代碼中coupon.name.

3.大神的Demo參考:


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

首先說明,html這樣寫沒有任何問題,動態的select的正確使用方法就是這樣。

下面是js代碼:

        var vm = new Vue({undefined
                el: '#app',
                data:{undefined
                    couponList:[
                        {undefined
                            id: 'A',
                            name: '優惠券1'
                        },
                        {undefined
                            id: '1',
                            name: '優惠券2'
                        },
                        {undefined
                            id: '2',
                            name: '優惠券3'
                        }
                    ],
                    couponSelected: '',
                },
                created(){undefined
            //如果沒有這句代碼,select中初始化會是空白的,默認選中就無法實現
                    this.couponSelected = this.couponList[0].id;

                },
                methods:{undefined

            getCouponSelected(){undefined

                        //獲取選中的優惠券

                        console.log(this.couponSelected)

                    }


   
   
   
           
  1. }
  2. })

上面的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)=&gt;{
    if((/^[-a-z0-9~!$%^&amp;*_=+}{\'?]+(\.[-a-z0-9~!$%^&amp;*_=+}{\'?]+)*@([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) =&gt; {
    this.isTableLoading = false;
    this.totalCount = result.totalCount;
    this.dataList = result.resultData;
    console.log(this.dataList);
  }, () =&gt; {
    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) =&gt; {
        this.inviteForm = {
          name:data.name,
          email:data.email,
          telephone:data.telephone
        }
      }, () =&gt; {})
  },
  //查看按鈕(ok)
  shandleModify(data){
    this.title = '查看用戶';
    this.addUserVisible1 = true;
    this.getUserById({
      id: data.id
    })
      .then((result) =&gt; {
        this.inviteForm1 = {
          name:data.name,
          email:data.email,
          telephone:data.telephone
        }
      }, () =&gt; {})
  },
  //執行增加或者修改(ok)
  handleInviteUser(){
    this.$refs['inviteForm'].validate((valid) =&gt; {
      if (valid) {
        this.isInviting = true;
        this.isTableLoading = true;
        (()=&gt;{
          if(this.currentUserInfo){
            this.inviteForm.id = this.currentUserInfo.id;
            return this.updateUser(this.inviteForm)
          }else{
            return this.inviteUser(this.inviteForm)
          }
        })()
          .then(()=&gt;{
            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) =&gt; {
              this.isTableLoading = false;
              this.totalCount = result.totalCount;
              this.dataList = result.resultData;
            }, () =&gt; {
              this.isTableLoading = false;
              this.$message.error('列表加載失敗!');
            })
          },()=&gt;{
            this.isInviting = false;
            this.$message({
              message: this.title+'失敗',
              type: 'error'
            });
          })
      }
    })
  },
  //刪除用戶(ok)
  handleDelete(userId, index) {
    this.$confirm('此操作將永久刪除數據, 是否繼續?', '提示', {
      confirmButtonText: '確定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() =&gt; {
      this.isTableLoading = true;
      this.deleteUser({
        id: userId
      })
        .then(() =&gt; {
          this.getUserList({
            pageSize: this.pageSize,
            pageNum: this.pageNum
          })
            .then((result) =&gt; {
              this.isTableLoading = false;
              this.totalCount = result.totalCount;
              this.dataList = result.resultData;
              this.$message({
                type: 'success',
                message: '刪除成功!'
              });
            }, () =&gt; {
              this.isTableLoading = false;
              this.$message.error('列表刷新失敗!');
            })
        }, () =&gt; {
          this.$message({
            type: 'error',
            message: '刪除失敗!'
          });
        })
    }).catch(() =&gt; {
      this.$message({
        type: 'info',
        message: '已取消刪除'
      });
    });
  },
  //凍結或者解凍用戶
  handleFreeze(userId, status, index){
    this.isTableLoading = true;
    this.updateUser({
      id:userId,
      status:status
    })
      .then((result) =&gt; {
        this.isTableLoading = false;
        this.dataList[index].status = status;
        this.$message({
          message: '修改成功!',
          type: 'success'
        });
      }, () =&gt; {
        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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。