前言:小寫轉大寫,可以用過濾器實現,但當使用 v-model 時就不行了,這里有解決方案。轉載請注明出處:https://www.cnblogs.com/yuxiaole/p/9289205.html
網站地址:我的個人vue+element ui demo網站
github地址:yuleGH github

可以采用過濾器實現
<html> <head> <title>測試</title> </head> <body> <div id="app"> <input id="val1" v-model="value1"> <br/> 顯示小寫轉大寫 : {{ value1 | upper}} </div> <!-- 引入組件庫 --> <script type="text/javascript" src="${ctx}/static/common/js/vue.js"></script> <script type="text/javascript"> new Vue({ el: "#app", data: { value1: "" }, filters: { upper: function (value) { if (!value) return ''; value = value.toString(); return value.toUpperCase(); } } }); </script> </body> </html>
v-model 中的實現
如果想要在使用 v-model 時,也要大寫轉小寫,就不能喝 filter 結合,因為這會報錯,這時應該換換種實現方式。可以采用計算屬性。
<html> <head> <title>測試</title> </head> <body> <div id="app"> 輸入框中直接輸入小寫轉大寫: <input v-model="value2Computed"> </div> <!-- 引入組件庫 --> <script type="text/javascript" src="${ctx}/static/common/js/vue.js"></script> <script type="text/javascript"> new Vue({ el: "#app", data: { value2: "" }, computed : { value2Computed : { get: function(){ return this.value2; }, set : function(val){ this.value2 = val.toUpperCase(); } } } }); </script> </body> </html>
form表單中實現,加上校驗
form表單中實現同v-model,不過校驗的 trigger 得是 change。
<html> <head> <title>測試</title> <link rel="stylesheet" href="../lib/elementui/theme-chalk/index.css" type="text/css"> </head> <body> <div id="app"> 3、form表單中 有校驗、並且小寫轉大小:trigger: 'change' <el-form :model="ruleForm" :rules="rules"> <el-form-item label="名稱(必須包含123)" prop="name"> <el-input v-model="nameComputed"></el-input> </el-form-item> </el-form> </div> <!-- 引入組件庫 --> <script type="text/javascript" src="../lib/vue.js"></script> <script type="text/javascript" src="../lib/elementui/index.js"></script> <script type="text/javascript"> var validateName = (rule, value, callback) => { if (value.indexOf("123") == -1) { callback(new Error('請輸入包含123')); } else { callback(); } }; new Vue({ el: "#app", data: { ruleForm : { name : "" }, rules : { 'name' : [ { required: true, message: '請輸入名稱', trigger: 'change' }, { min: 3, max: 5, message: '長度在 3 到 5 個字符', trigger: 'change' }, { validator: validateName, trigger: 'change' } ] } }, computed : { nameComputed : { get: function(){ return this.ruleForm.name; }, set : function(val){ this.ruleForm.name = val.toUpperCase(); } } } }); </script> </body> </html>
轉載請注明出處:https://www.cnblogs.com/yuxiaole/p/9289205.html
