Vue 中优雅的使用第三方库

2022-10-05 08:17:52

全局

优点:不依赖 vue 或任何,避免了挂载 Vue 下有些地方获取不到 this 从而不能用的情况。
缺点:服务端没有 window,window = undefined , window.xx 报错
entry.js

window._=require('loadsh');

Components.vue

created(){const{ value}=axios('')this.list=   _.isEmpty(value)?['暂无数据']: value}

挂载至 Vue.prototype

Object.defineProperty

通过 Object.defineProperty 的 descriptor 定义属性默认只读

import axiosfrom'axios'

Object.defineProperty(Vue.prototype,'$_axios',{ value: axios})

Vue.prototype.$_axios

作为对比,直接操作原型也是可以的,但是这样会被重写

import axiosfrom'axios'

Vue.prototype.$_axios= axios
Vue.prototype.$_axios='axios'// Vue.prototype.$_axios -> 'axios'

插件形式注册

import axiosfrom'axios';exportdefault{install(Vue, name='$axios'){
    Object.defineProperty(Vue.prototype, name,{ value: axios});}}

entry.js

import AxiosPluginfrom'./axios.js';
Vue.use(AxiosPlugin,'$axios');

每个文件中引入

多个组件公用的话不建议这种方式

import axiosfrom'axios';exportdefault{created(){axios('')}}
  • 作者:如果有了可惜
  • 原文链接:https://blog.csdn.net/jufjzq/article/details/108863754
    更新时间:2022-10-05 08:17:52