vue自定義插件及使用


一、Vue插件有什么用


插件通常會為 Vue 添加全局功能。
所謂全局:
即不需要像組件那樣,每次使用他前都需要先引入一次。對於插件只要在最開始引入一次,在任何組件就可以直接使用。(類似於我們在window上添加的方法屬性那樣,任何地方都可以用)
插件能實現的功能沒有限制,不過常見下面幾種:

通過插件,添加全局方法或者屬性
通過插件,添加全局資源:指令/過濾器/過渡等
通過插件(使用全局 mixin 方法),添加一些組件選項
通過插件,添加 Vue 實例方法,通過把它們添加到 Vue.prototype 上實現。
一個庫,提供自己的 API,同時提供上面提到的一個或多個功能,如 vue-router

二、插件原理

所謂vue插件其實就是一個簡單的js對象而已,然后這個插件對象有一個公開屬性 install ,他的值為一個函數,此函數接受兩個參數。第一個參數是 Vue 構造器 , 第二個參數是一個可選的選項對象。

 

三、插件編寫及舉例

 1、編寫插件

 

// install函數

let Valid = {}
Valid.install = function(Vue, options = { triggEvent: "input" }) {
    // static props 靜態屬性
    // Vue.t1703C="hello everyone"
    // Vue.t1703C = "1703C"
    // console.log(this) this指向vue  可一直往上查找,可查找到new Vue


    // 所有需要驗證的組成一個列表
    let regList = [{
        "type": "phone",
        "RegExp": /^1[345679]\d{9}$/,
        "msg": "手機需要11位數字"
    }, {
        "type": "pwd",
        "RegExp": /\w{6,9}/
    }, {
        "type": "code",
        "RegExp": /\d{4}/
    }]

    Vue.directive("valid", {
        bind(el, binding) {
            // el:dom節點 binding:對象(可使用value)
            // console.log(binding)

            // 失去焦點事件
            el.addEventListener(options.triggEvent, function(e) {
                // console.log(e.target.value)

                // 找到符合條件的對象
                let validObj = regList.find(item => item.type === binding.value)
                if (validObj.RegExp.test(e.target.value)) {
                    console.log("驗證通過")
                    e.target.classList.remove(options.errorClass)
                } else {
                    // let span = document.createElement("span");
                    // span.innerText = validObj.msg
                    // e.target.parentNode.appendChild(span)
                    console.log("格式錯誤")
                    e.target.classList.add(options.errorClass)
                }

            })
        }
    })
}
export default Valid

2、使用
使用插件的時候,在main.js入口文件import引入,再使用use()方法使用即可

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
//引入axios import $http
from "@/plugins/$http";
//引入自定義插件插件 v-vaild import Valid
from "@/plugins/validator"; Vue.config.productionTip = false Vue.use(ElementUI);
//全局的axios Vue.use($http, { timeout:
2000 });
//自定義插件 Vue.use(Valid, { triggEvent:
"blur", //triggEvent:事件 value值必須是字符串, errorClass: "vaild-error" //errorClass:類名 }) new Vue({ router, store, render: h => h(App) // created() { // console.log(this) // }, }).$mount('#app')

3、在組件中訪問

<template>
    <div class="login"> 
        <header class="loginHeader">登錄/注冊</header>
        <main class="loginMain">
            <div class="con">
          //在這里使用了自定義插件v-vaild <input v-valid="'phone'" placeholder="請輸入姓名" v-model="user" class="user"/> <input v-valid="'pwd'" placeholder="請輸入密碼" v-model="password" show-password class="pwd"/> <input v-valid="'code'" placeholder="請輸入驗證碼" v-model="code" class="code"/> <span v-html="this.svg" class="captch" @click="upDataCaptch"></span> <el-button type="primary" class="btn" @click="handleLogin">登錄</el-button> <router-link to="/register">注冊</router-link> </div> </main> </div> </template> <script> export default { props:{ }, components:{ }, data(){ return { user:"", password:"", code:"", svg:"" } }, computed:{ }, methods:{ handleLogin(){ let data={username:this.user,password:this.password,captcha:this.code} this.$http.post("/api/buyer/user/login",data).then(res=>{ window.sessionStorage.setItem("token",res.token) console.log(res) if(res.code===1){ this.$router.push("/list") } }).finally(()=>{ // 登錄失敗再次調用 this.upDataCaptch() }) }, upDataCaptch(){ // 每次點擊都請求一次驗證碼 this.$http.get("/api/buyer/user/captcha").then(res=>{ console.log(res) this.svg=res.data }) } }, created(){ // 初始化 this.upDataCaptch() }, mounted(){ } } </script> <style lang="scss"> *{ padding: 0; margin: 0; list-style: none; } html,body{ width: 100%; height: 100%; font-size: calc(100/750*100vw); } .login{ width: 100%; height: 100%; font-size: calc(.16rem*2); display: flex; flex-direction: column; background: #ebebec; } .loginHeader{ width: 100%; height: calc(.5rem*2); display: flex; justify-content: center; align-items: center; } .loginMain{ flex: 1; overflow: auto; } .con{ width: 80%; height: 80%; margin: 0 auto; input{ width: 100%; height: calc(.3rem*2); } .user{ margin-top: 20px; } .pwd{ margin-top: 20px; } .btn{ width: 100%; height: 10%; margin-top: 20px; } .code{ margin-top: 20px; width: 50%; } .captch{ margin-top: 20px; } } </style>

 


免責聲明!

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



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM