30-Vue脚手架-plugin插件

发布时间 2023-10-27 09:25:28作者: 马铃薯1

plugin插件

功能:用于增强Vue

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

 

src/plugins.js(定义插件

// 定义插件(默认暴露)
export default {
    install(Vue){
        console.log("@@@install")
        console.log(Vue)

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

        // 2.自定义全局指令
        Vue.directive("fbind",{
            // bind(element,binding)回调函数,指令与元素成功绑定时调用
            bind(element,binding){
                console.log("bind")
                element.value = binding.value
            },
            // inserted(element,binding)回调函数,指令所在元素被插入页面时调用
            inserted(element){
                console.log("inserted")
                element.focus()
            },
            // update(element,binding)回调函数,指令所在模板结构被重新解析时调用
            update(element,binding){
                console.log("update")
                element.value = binding.value
            }
        })

        // 3.定义混入
        Vue.mixin({
            data(){
                return{
                    x:100,
                    y:200
                }
            }
        })

        // 4.给Vue原型上添加一个方法(vm和vc就都能用了)
        Vue.prototype.hello = ()=>{
            alert("你好啊")
        }

    }
}

src/mixin.js (使用插件)

import Vue from "vue"
import App from "./App.vue"

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

// 阻止 vue 在启动时生成生产提示
Vue.config.productionTip = false

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


new Vue({
    el:"#app",
    render:h => h(App)
})

src/components/Student.vue

<template>
  <div>
    <h2>学生姓名:{{name}}</h2>
    <h2>学生性别:{{sex}}</h2>
    <!----plugins插件里面,自定义了v-fbind指令-->
    <input type="text" v-fbind:value="name">
  </div>
</template>

<script>
  export default{
    // eslint-disable-next-line vue/multi-word-component-names
    name:"Student",
    data(){
      return{
        name:"马铃薯",
        sex:"",
      }
    }
  }

</script>

src/components/School.vue

<template>
  <div>
    <!--plugins插件里面,定义了mySlice过滤器-->
    <h2>学校名称:{{name | mySlice}}</h2>
    <h2>学校地址:{{address}}</h2>
    <button @click="test">点我测试一个hello方法</button>
  </div>
</template>

<script>
  export default{
    // eslint-disable-next-line vue/multi-word-component-names
    name:"School",
    data(){
      return{
        name:"东华理工大学",
        address:"江西南昌",
      }
    },
    methods:{
      test(){
        this.hello()
      }
    }
  }

</script>

src/App.vue(没有变动)

<template>
  <div>
    <!--学生的信息-->
    <Student></Student>
    <hr/>
    <!--学校的信息-->
    <School></School>
  </div>
</template>

<script>
  // 引入Student组件
  import Student from "@/components/Student.vue";
  // 引入School组件
  import School from "@/components/School.vue";

  export default{
    name:"App",
    components: {
      School: School,
      Student: Student
    }
  }
</script>