Vue 插件

功能:增强 Vue

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


定义插件

对象.install = function (Vue, options) {

	// 添加全局过滤器
	Vue.filter(...)
	
	 // 添加全局指令
	 Vue.directive(...)
	 
	 // 配置全局混入
	 Vue.mixin(...)
	 
	 // 添加实例方法
	 Vue.prototype.$myMethod = function () {...}
	 Vue.prototype.$myProperty = function = xxx
}

使用插件Vue.use()



实例

src 文件结构

|-- src
    |-- App.vue
    |-- main.js
    |-- plugins.js
    |-- components
        |-- School.vue
        |-- Student.vue

App.vue

<template>
    <div id="app">
        <School/>
        <hr>
        <Student/>
    </div>
</template>

<script>
    import School from "@/components/School";
    import Student from "@/components/Student";

    export default {
        name: 'App',
        components: {
            School,
            Student
        },
        data() {
            return {}
        }
    }
</script>

main.js

import Vue from 'vue'
import App from './App.vue'

// 引入插件
import plugins from "@/plugins";

Vue.config.productionTip = false

// 应用插件
Vue.use(plugins)

new Vue({
    render: h => h(App),
}).$mount('#app')

plugins.js

export default {
    install(Vue) {
        console.log('@ install', Vue)

        // 全局过滤器
        Vue.filter('mySlice', function (value) {
            return value.slice(0, 3)
        })

        // 定义混入
        Vue.mixin({
            data() {
                return {
                    a: 1,
                    b: 2
                }
            }
        })

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

School.vue

<template>
    <div class="school">
        <h2>学校名称:{{name | mySlice}}</h2>
        <h2>学校地址:{{address}}</h2>
        <button @click="test">测试 Hello</button>
    </div>
</template>

<script>
    export default {
        name: 'School',
        data() {
            return {
                name: 'ABCabc',
                address: '长沙',
            }
        },
        methods: {
            test(){
                this.hello()
            }
        }
    }
</script>

Student.vue

<template>
    <div class="school">
        <h2>姓名:{{name}}</h2>
        <h2>性别:{{sex}}</h2>
    </div>
</template>

<script>
    export default {
        name: 'Student',
        data() {
            return {
                name: '张三',
                sex: '男'
            }
        }
    }
</script>


posted @ 2022-05-06 11:17  春暖花开鸟  阅读(44)  评论(0编辑  收藏  举报