Vue中插件的使用

插件

作用:插件的作用是增强Vue。
本质:插件的本质是一个对象,且是一个具有install方法的对象。

install方法的第一个参数是Vue对象,第二个及以后的参数是开发者自定义传入的。

install方法的第一个参数是Vue,所以 自定义指令Vue.directive())、自定义过滤器 (Vue.filter())、自定义混入Vue.mixin())都可以在写在install方法里。看个具体的例子。

定义插件:myPlugin.js

插件的install方法中,

  • 自定义了指令:v-fbind,指令功能类似于v-bind,且输入框自动获得焦点。
  • 自定义了过滤器:slicer,只截取了原字符串的前4个字符。
  • 自定义了混入:使得每个组件都有{x:100,y:100}这两个数据。
export default {
    install(Vue,a,b){
        console.log("installing myPlugin",a,b);

        Vue.directive("fbind",{
            bind(element,binding){
                element.value = binding.value;
            },
            inserted(element,binding){
                element.value = binding.value;
                element.focus();
            },
            update(element,binding){
                element.value = binding.value;
                element.focus();
            }
        })

        Vue.filter("slicer",function(value){
            return value.slice(0,4)
        })

        Vue.mixin({
            data(){
                return {
                    x:100,
                    y:200
                }
            }
        })
    }
}
 

定义组件:Company.vue

组件实现中,使用了上面自定义的指令v-fbind、过滤器slicer和混入。

<template>
  <div>
      <h2>公司名称:{{name}}</h2>
      <h2>公司地址:{{address}}</h2>
      <h2>裁剪后的公司名称:{{ name | slicer}}</h2>
      <input type="text" v-fbind="name">
  </div>
</template>

<script>
export default {
    data(){
        return {
            name:"五哈科技有限公司",
            address:"上海宝山"
        }
    }
}
</script>

定义顶层组件App.vue

<template>
    <Company/>
</template>

<script>
import Company from "./components/Company";
export default {
    name:"App",
    components:{
        Company
    }
}
</script>
 

使用插件:main.js,入口文件

通过Vue.use()引入插件。
同时可以看到,Vue.use的第二、第三个参数是开发者自定义传入的,它们将成为插件install方法的第二个、第三个参数。

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

Vue.config.productionTip = false;

Vue.use(myPlugin,"hello","world");

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

 运行

最后,npm run serve 启动应用,访问地址localhost:8080。
在这里插入图片描述

 

热门组件库

1 使用第三方插件

https://github.com/vuejs/awesome-vue#components–libraries

集合了来自社区贡献的数以千计的插件和库。

2 使用第三方UI框架

饿了么UED团队推出的vue

前端框架:

PC框架:

  (element UI , iview)

  element UI 官网:http://element.eleme.io/

  element UI github:https://github.com/ElemeFE/element

移动端框架:

  (mint UI)

  mint UI官网:https://mint-ui.github.io/docs/

  mint UI github:https://github.com/ElemeFE/mint-ui

elementui的使用

https://element.eleme.cn/#/zh-CN/component/quickstart

1 安装

cnpm i element-ui -S

2 配置完整引入 

 在 main.js 中写入以下内容

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI);

以后直接使用elementui提供的全局组件即可。

3. 使用

  去官网看到好的,复制贴到你的项目中即可

posted @ 2023-02-22 15:42  莫~慌  阅读(207)  评论(0编辑  收藏  举报