--- tags: Vue 3 VeeValidation 驗證 --- # 使用 CDN 來載入 Vee-validate >使用CLI來匯入的Vee-validate[連結](https://hackmd.io/fSDVyMA2Q5yl591nOLNkVA?view) ![](https://i.imgur.com/o6eQ4vn.jpg) ## 步驟一:載入CDN ```htmlembedded= <!-- 載入CDN --> <script src="https://cdnjs.cloudflare.com/ajax/libs/vee-validate/4.1.17/vee-validate.min.js"></script> <script type="module"></script> ``` ## 步驟二:綁定components ```javascript= console.log(VeeValidate); // 查看VeeValidate資料 const app = Vue.createApp({ components: { VForm: VeeValidate.Form, VField: VeeValidate.Field, VErrorMessage: VeeValidate.ErrorMessage, }, }); app.mount('#app'); ``` ## 步驟三&步驟四: * 把原本html屬性改成components屬性 * v-form 加上 v-solt 把資料傳到外部 ```htmlembedded= <!-- 原本寫法: --> <form @submit.preventDefault="onSubmit"> <input type="text" placeholder="userName"> </form> <!-- 改寫: --> <v-form @submit.preventDefault="onSubmit" v-slot="{ errors }"> {{ errors }} <v-field name="userName" type="text" placeholder="userName" ></v-field> </v-form> ``` ## 步驟五: * v-field 加上rules(規則)來綁定方法 * 當方法不等於value(意思是指:沒有輸入值),就會傳請輸入內容,相反則回傳true(意思指:不會傳任何文字到畫面上) ```htmlembedded= <v-field name="userName" type="text" placeholder="userName" :rules="isRequired"></v-field> ``` ```javascript= methods: { isRequired(value){ if(!value){ console.log(VeeValidate); return '請輸入內容'; } return true; }, }, ``` ## 步驟六: * v-field & v-error-message 所綁定的 name 名稱要互相對應 ```htmlembedded= <v-field name="userName" type="text" placeholder="userName" ></v-field> <v-error-message name="userName">請填寫名稱</v-error-message> <v-field name="userEmail" type="text" placeholder="userEmail" :rules="isRequired"></v-field> <v-error-message name="userEmail">請填寫EMAIL</v-error-message> ``` ## 步驟七: * onSubmit 會與 isRequired 做對應,當如果尚未輸入值直接按送出,isRequired也會跟著被觸發,但 onSubmit不會被觸發;直到輸入值之後 isRequired 會再次被觸發(觸發:return true) 且 onSubmit 也會被觸發。 ```htmlembedded= <v-form @submit.preventDefault="onSubmit" v-slot="{ errors }"> {{ errors }} <v-field name="userName" type="text" placeholder="userName" :rules="isRequired"></v-field> <v-error-message name="userName">請填寫名稱</v-error-message> <v-field name="userEmail" type="text" placeholder="userEmail" :rules="isRequired"></v-field> <v-error-message name="userEmail">請填寫EMAIL</v-error-message> <button>送出</button> </v-form> ``` ```javascript= methods: { onSubmit(value) { console.log(value) }, isRequired(value){ if(!value){ console.log(VeeValidate); return '請輸入內容'; } return true; }, }, ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up