Vue-手写插件

446 阅读1分钟

初步了解

功能:用于增强Vue

本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。

使用插件

// main.js

import plugins from './plugins'

Vue.use(plugins)

定义一个插件

// plugins.js
export default {
    install(Vue) {
        console.log('使用插件了')

        // 自定义全局获取焦点指令
        Vue.directive('focus',{
            inserted: function(el){
                // el代表绑定的元素
                el.focus();
            }
        })

        // 定义一个全局过滤器 ---- 字母转大写
        Vue.filter('toUpperCase', function(val){
            return val.toUpperCase();
        });

        // 添加一个混入
        Vue.mixin({
            data() {
                return {
                    mixData: '这是mixin中数据',
                    x: 100,
                }
            },
            created () {
              console.log(this.y)
            },
            methods: {
                handleClick() {
                    console.log(this.name)
                }
            },
            computed: {
                showNumber() {
                    return this.x + this.y
                }
            }
        })

        // 给Vue原型上添加一个方法
        Vue.prototype.hello = () => {
            alert("你好啊")
        }
    }
}