博客
关于我
Vue 使用Use、prototype自定义全局插件
阅读量:454 次
发布时间:2019-03-06

本文共 1221 字,大约阅读时间需要 4 分钟。

开发环境配置与Vue全局插件自定义实现

Vue全局插件的创建与使用

一、开发环境配置

使用Win 10系统安装node.js环境

下载地址:node-v10.15.3-x64.msi

二、插件实现方式

  • 创建src目录下的plugin子目录

  • 在plugin目录下创建sendRequest.js文件

  • export function sendRequest() {console.log("send request by sendRequest Plugin");}

    1. 在plugin目录下创建customPlugin.js文件
    2. import sendRequest from "./sendRequest";export default sendRequest;

      1. 在plugin目录下创建index.js文件
      2. import customPlugin from "./customPlugin";const install = Vue => {if (install.installed) return;install.installed = true;Object.defineProperty(Vue.prototype, "$customPlugin", {get() {return customPlugin;}});};export default install;

        注意:Object.defineProperty方法用于在Vue原型上挂载插件对象

        五、在主文件中使用插件

        在main.js文件中添加以下内容:

        import Vue from "vue";import App from "./App";import router from "./router";import customPlugin from "@/plugin/index";

        Vue.use(customPlugin);Vue.config.productionTip = false;

        new Vue({el: "#app",router,components: { App },template: "

        "});

        六、在.vue组件中引用插件方法

        在methods中定义方法:

        methods: {sendRequest() {this.$customPlugin.sendRequest();}}

        关于插件调用方法

        可在js文件中直接引入customPlugin,使用Vue.prototype.$customPlugin.sendRequest()的方式调用

        需要注意的是,直接使用pluginName.fileModuleName.functionName()可能会导致fileModuleName为undefined的问题,建议使用Vue.prototype.$pluginName.fileModuleName.functionName()的方式调用

    转载地址:http://smvfz.baihongyu.com/

    你可能感兴趣的文章
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>
    npm设置源地址,npm官方地址
    查看>>
    npm设置镜像如淘宝:http://npm.taobao.org/
    查看>>
    npm配置安装最新淘宝镜像,旧镜像会errror
    查看>>
    NPM酷库052:sax,按流解析XML
    查看>>
    npm错误 gyp错误 vs版本不对 msvs_version不兼容
    查看>>
    npm错误Error: Cannot find module ‘postcss-loader‘
    查看>>
    npm,yarn,cnpm 的区别
    查看>>