全局
优点:不依赖 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 axios from 'axios'
Object.defineProperty(Vue.prototype, '$_axios', { value: axios })
Vue.prototype.$_axios
作为对比,直接操作原型也是可以的,但是这样会被重写
import axios from 'axios'
Vue.prototype.$_axios = axios
Vue.prototype.$_axios = 'axios'
// Vue.prototype.$_axios -> 'axios'
插件形式注册
import axios from 'axios';
export default {
install(Vue, name = '$axios') {
Object.defineProperty(Vue.prototype, name, { value: axios });
}
}
entry.js
import AxiosPlugin from './axios.js';
Vue.use(AxiosPlugin, '$axios');
每个文件中引入
多个组件公用的话不建议这种方式
import axios from 'axios';
export default {
created() {
axios('')
}
}