vue按需引入,iview-UI库

1,581 阅读1分钟

按需引用,借助插件 babel-plugin-import可以实现按需加载组件,减少文件体积。首先安装,并在文件 .babelrc 中配置:

//npm安装
npm install babel-plugin-import --save-dev

// .babelrc配置文件添加如下代码:
{
  "plugins": [["import", {
    "libraryName": "iview",
    "libraryDirectory": "src/components"
  }]]
}

然后这样按需引入组件,就可以减小体积了:

import 'iview/dist/styles/iview.css';
import { 
    Button, 
    Icon,
    Message,
    Alert,
    Notice,
    Spin,
} from 'iview';

Vue.component('Button', Button);
Vue.component('Icon', Icon);
Vue.component('Alert', Alert);
//像通过$Message这种调用的组件,不能用component注册,
//需要把属性绑到Vue实例上,即在main.js里面 import以后,
//Vue.prototype.$Message = Message 这样注册
Vue.prototype.$Message = Message
Vue.prototype.$Notice = Notice
Vue.prototype.$Spin = Spin

Message或Notice,Spin组件提示类,在组件中调用方式:

this.$Message.info('This is a info tip');

this.$Notice.open({
    title: '标题',
    desc: '内容'
});

this.$Spin.show();
setTimeout(() => {
    this.$Spin.hide();
}, 3000);

axios封装中的调用方式:

//需要在axios.js单独引入
import { 
    Message,
    Alert,
    Notice,
    Spin,
} from 'iview';

//使用:
Message.info('This is a info tip');
Spin.show();