一、部分导入导出
部分导出和部分导入的优势,当资源比较大时建使用部分导出,这样一来使用者可以使用部分导入来减少资源体积,
比如element-ui官方的就推荐使用部分导入来减少项目体积,因为element-ui是一个十分庞大的框架,如果只用到其中的一部分组件,那么只将用到的组件导入就可以了。
export function helloWorld(){
conselo.log("Hello World");
}
export function myTestFuntion(){
conselo.log("this's myTestFuntion function");
}
2、部分导入的另一种写法
var helloWorld = function() {
conselo.log("Hello World");
}
var myTestFuntion = function() {
conselo.log("this's myTestFuntion function");
}
export helloWorld;
export myTestFuntion;
3、部分导入,只需要引入需要的资源
import { helloWorld } from "./utils.js" //只导入utils.js中的helloWorld方法
helloWorld(); //执行utils.js中的helloWorld方法
4、部分导入,引入全部的资源,比如如果我们需要utils.js中的全部资源则可以全部导入
import * as utils from "./utils.js" //导入全部的资源,utils为别名,在调用时使用
utils.helloWorld(); //执行utils.js中的helloWorld方法
utils.myTestFuntion(); //执行utils.js中的myTestFuntion方法
注意,import HelloWorld from ‘@/components/HelloWorld’这种使用了@的导入方式,’@'代表src下的目录
二、全部导入导出
如果使用全部导出,那么使用者在导入时则必须全部导入。
1、全部导出
var helloWorld=function(){
conselo.log("Hello World");
}
var myTestFuntion=function(){
conselo.log("this's myTestFuntion function");
}
export default {
helloWorld,
myTestFuntion
}
2、全部导入
当用export default 导出的时候,随便起一个变量名导入即可
import utils from "./utils.js"
utils.helloWorld();
utils.myTestFuntion();
备注:
1、当import引入外部,比如modules中的依赖包的时候,不需要相对路径,直接引入包名即可,形如:import axios from 'axios’或者import Vue from ‘vue’;
2、一个js文件中可以有多个export,但只能有一个export default
三、导入之后,两种调用方式
1、在当前页面
在上面的例子中,都是在当前页面调用,直接http.get或http.post就行,在此不再赘述
2、全局变量
更多的是全局变量,比如封装的get或post请求方法等
import http from './utils/http';
// 挂载至全局
Vue.prototype.http = http
引入之后,借助Vue的prototype属性将变量挂载到全局中,这样在任何.vue页面中,直接用this.http.get或this.http.post即可,别忘了this,注意this作用域