# 擴充插件 plugins ## 外部套件引用 * 載入方式:使用 CDN 或使用 npm * 運用方式:<a href="https://www.npmjs.com/package/vue-axios">app.use()</a> 或 <a href="https://vee-validate.logaretm.com/v4/guide/components/validation#field-level-validation">元件的形式載入</a> 啟用。(另有指令等各種 Vue 的語法形式) ### 使用外部套件注意事項: * 需多注意可搭配的版本號 * 更新頻率 * 使用人數 ## 範例:載入 VeeValidate 驗證套件 使用CDN方式載入外部套件 ```javascript= <script src="https://cdnjs.cloudflare.com/ajax/libs/vee-validate/4.1.17/vee-validate.min.js"></script> ``` 即可引用了內部套件 ```javascript= console.log(VeeValidate); ``` ![](https://i.imgur.com/KRdQ40c.png) components 啟用 VeeValidate方式加入屬性,(VForm)為 v-form縮寫方式 ```javascript= components: { // Components were renamed to avoid conflicts of HTML form element without a vue compiler VForm: VeeValidate.Form, VField: VeeValidate.Field, ErrorMessage: VeeValidate.ErrorMessage, }, ``` 在運用時我們會依照幾個步驟來載入至HTML中 * 在表單元件中我們會對應components中的VForm名稱,所以表單原本的form就修改成v-form ```htmlembedded= <v-form @submit="onSubmit"> ``` * 那在input中我們也改成v-field,v-field是個元件 所以要有 </v-field>標籤做結尾 ```htmlembedded= <v-form @submit="onSubmit"> <v-field name="name" type="text" placeholder="Who are you"> </v-field> <span>請填寫此欄位</span> <button>Submit</button> </v-form> ``` * 我們將v-slot屬性資源擴展給外部來使用、並先定義內容 ```javascript= <v-form @submit="onSubmit" v-slot="{ errors }"> {{ errors }} ``` * 利用 rules 自定義一個屬性及驗證的函式 ```htmlembedded= <v-field name="name" type="text" placeholder="Who are you" :rules="isRequired" > </v-field ``` 在methods 定義一個驗證函式,如果input沒有填寫沒有值(value)傳入、將回傳結果訊息 ```javascript= methods: { isRequired(value){ if(!value){ return "此欄位必填喔" } return true ; } }, ``` 在欄位驗證時就會出現name=""的錯誤訊息、即規則的結果 ![](https://i.imgur.com/hogViGd.png) 那將name裡面的值改成 name="此欄位名稱" 對應也會修改 ![](https://i.imgur.com/iROnTWz.png) * 運用==ErrorMessage==修改Span標籤顯示訊息,這邊的name也對應 **v-field** 的name ```htmlembedded= <error-message name="此欄位名稱"></error-message> ``` <div class="alert alert-success text-center" role="alert"> @submit="onSubmit" 同時也會驗證是否表單有填寫、若無填寫也無法送出表單 </div> ```htmlembedded= <v-form @submit="onSubmit" v-slot="{ errors }"> ``` * @submit="onSubmit"在送出後,也會將input值傳出來 ```javascript= onSubmit(value) { console.log(value) }, ``` ![](https://i.imgur.com/IYwIOTv.png)
{"metaMigratedAt":"2023-06-16T11:15:05.106Z","metaMigratedFrom":"YAML","title":"擴充插件 plugins","breaks":true,"contributors":"[{\"id\":\"c05b36ac-d774-4e45-8fc3-5e50c9be5123\",\"add\":2359,\"del\":20}]"}
Expand menu