Use of Vue custom plugins

 Binding method through Vue instance:

 Create the filter filter in the plugins.js file, defining a method that returns only the first four characters.

export default {
    install(Vue){
        // 定义过滤器
        Vue.filter('mySlice',function(value){
            return value.slice(0,4);
        })
    }
}


Since we introduced it in the main.js file before, it can be used directly on the Home.vue page.

<template>
    <div>
        <h1>{
     
     { title | mySlice }}</h1>
    </div>
</template>

<script>
export default {
    name: 'Home',
    data() {
        return {
            title: "青青草原喜洋洋股份有限公司"
        }
    }
}
</script>

Note : This plugin is equivalent to registering a filter globally, which can be used anywhere.

 

 Note : In addition to binding through the Vue instance, you can also bind the method to the Vue prototype, so that both the Vue instance and the component can use this method.

 Binding methods through the prototype chain:

Add a custom method to Vue's prototype in the plugins.js file.

export default {
    install(Vue){
        // 定义过滤器
        Vue.filter('mySlice',function(value){
            return value.slice(0,4);
        })

        // 通过原型链创建方法
        Vue.prototype.hello = () => {
            alert("你好呀!");
        }
    }
}

Then create a click event using this method on the Home.vue page.

<template>
    <div>
        <h1 @click="hello">{
     
     { title | mySlice }}</h1>
    </div>
</template>

<script>
export default {
    name: 'Home',
    data() {
        return {
            title: "青青草原喜洋洋股份有限公司"
        }
    }
}
</script>

Note : Since Vue instances and components share a prototype object, this method can be used anywhere.

 

 

 The custom plugin receives parameters:

The plug-in can also receive custom parameters, just pass and receive when referencing. Example: main.js file

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

// 引入插件
import plugins from './plugins'

Vue.config.productionTip = false

// 使用插件,并传递参数
Vue.use(plugins,1,2,3)

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

Then receive it in the install method in the plugins.js file.

export default {
    install(Vue,a,b,c){
        console.log(Vue);
        console.log(a,b,c); // 1 2 3

        // 定义过滤器
        Vue.filter('mySlice',function(value){
            return value.slice(0,4);
        })

        // 通过原型链创建方法
        Vue.prototype.hello = () => {
            alert("你好呀!");
        }
    }
}

Note : The first parameter of the install method is always the constructor of the Vue instance, and the custom parameters are received later

 

Original author: Wu Xiaotang

Creation time: 2023.5.28
 

Guess you like

Origin blog.csdn.net/xiaowude_boke/article/details/130909847