一、import的用法

html文件中,通过script标签引入js文件;
vue中通过import xxx from xxx的方式导入文件,不光可以导入js文件,还可以导入css文件等多种类型的文件。


1. 语法

import xxx from xxx

from前的:
“xxx”指的是为导入的文件起的一个名称,不是指导入的文件的名称,相当于变量名

from后的:
“xxx路径”指的是文件的相对路径

2. 使用场景

2.1 在某个.vue文件,或js文件(例如router.js)中引入vue组件

import Header from '@/components/header'
import Footer from '../components/footer'

这种方式的引入可以省略文件的后缀名

2.2 在某个.vue文件中引入css和js

import  '../assets/css/style.css'
import  '../assets/js/index.js'

也可以嵌套在style标签中引入css

<style>
    @import "../assets/css/style.css";
</style>

注意:这个@和webpack.base.conf.js文件中代表src的@不是一回事,这个只是一种引入css的一种方式。

2.3 引入工具类

2.3.1 引入单个方法
import {axiosfetch} from './util';

下面是导出文件的写法,axiosfetch需要先在另一个js文件中使用export导出:

export function axiosfetch(options) {
 //...
} 
2.3.2 引入成组的方法
// *:导入tools.js中的全部方法
// as:重命名
import * as tools from './libs/tools'

在vue中使用 :

Vue.prototype.$tools = tools

直接用 this.$tools.method调用就可以了。

二. export 与 export default 的用法

exportimport 是es6中新增模块功能最主要的两个命令。

1. 语法

1.exportexport default 均可用于导出常量、函数、文件、模块等;
2.在一个文件或模块中,export、import 可以有多个,export default 仅有一个;
3. 通过 export 方式导出,在导入时要加 { } ,export default 则不需要 { } 。

2. 使用场景

2.1 export

a.js:

export const str = 'hello world'
export const num = 0
export func() {
	console.log('I am a funnction')
}
  • 在.vue或.js文件中导入:
import {str,num,func} from './a';
  • 如果想对func重命名可以这样导入:
import {str,num,func as _func} from './a';

在需要的地方调用_func:

// 相当于直接调用func()
_func()
  • 导入全部的资源
// _A为别名,在调用时使用
import * as _A from './a';

在需要的地方调用func:

_A.func();

2.2 export default

b.js:

export default {
	str: 'hello world',
	num: 0,
	func: () => {
		console.log('I am a funnction')
	}
}

在.vue 或 .js文件中导入:

import b from './b';
// 获取a中的变量
console.log(b.str);
console.log(b.num);
b.func();
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐