自己寫個vue.js外掛(3):外掛裡面包含子元件
阿新 • • 發佈:2019-02-15
前面我們把文字框驗證的錯誤提示部分封裝到了validate.js
外掛中。
還不夠徹底,我們應該把文字框也封裝儘量,弄成子元件的形式。
1.這是使用者名稱文字框,原本是在user-name.vue
元件中的
input type="text" v-uname="username" v-model="username" v-on:change="userNameChange" class="form-control" :placeholder="username">
2.我們要做到在user-name.vue
只使用元件的形式
<validate-text></validate-text >
3.下面就到validate.js
中看看,是怎麼實現的
// 驗證文字框,自帶元件
Vue.component("validate-text",{
template: '<div><input type="text" class="form-control" v-model="textValue" />' + '<label v-if="showErrorLabel" class="label label-danger">使用者名稱不合法</label></div>',
data(){
return {textValue:""}
},
// 計算屬性
computed:{
showErrorLabel(){
if(/\w{6,20}/.test(this.textValue) || this.textValue == ""){
// 驗證通過,不提示錯誤
return false;
}
return true;
}
}
})