import在vue中使用
一、import的使用
在Vue 3中,使用import语法可以导入其他模块、组件或库。Vue 3支持使用ES模块的标准导入语法。以下是一些常见的import语法示例:
1、导入单个模块或组件
import { 模块名 } from '模块路径';
示例:
import { ref, reactive } from 'vue';
在上述示例中,我们使用import语法从vue模块中导入了ref和reactive两个函数。
2、导入整个模块或库
import * as 模块名 from '模块路径';
示例:
import * as axios from 'axios';
在上述示例中,我们使用import语法将整个axios库导入为一个命名空间对象。
3、导入默认导出
import 默认导出名称 from '模块路径';
示例:
import Vue from 'vue';
在上述示例中,我们使用import语法将vue模块的默认导出(通常是Vue构造函数)导入为Vue变量。
二、自定义模块并import
在前端编程的过程中,会经常使用import导入的方式引入一些js方法或公用方法,但在vue中使用时需要注意,在script中可以直接使用引入的方法,在vue模板中直接使用时,会报方法不存在。
1、需要在methods中申明引入的方法,或通过自定义方法返回
<template>
<div>
<p>import中的常量使用:{{ getPI() }}</p>
<p>使用import导入的方法:{{ test2() }}</p>
</div>
</template>
<script>
// 通过import导入常量或方法
import comm, { test2, test3 } from './comm.js';
export default {
data() {
return {};
},
mounted() {
//直接使用import导入的方法
console.log('test', comm.test());
console.log('test2', test2());
},
methods: {
// 在methods中申明的import方法,可以tmplate中直接使用
test2,
// 通过方法可以直接使用import引入的方法
getPI() {
return comm.PI;
}
}
};
</script>
<style lang="scss" scoped></style>
function nameJoin(name) { return `you name id ${name}`; } function test() { return 'test from comm.js'; } function test2() { return 'test2'; } function test3() { return 'test3'; } const PI = 3.14; // 默认导出(每个模块只能有一个) export default { nameJoin, test, PI }; // 直接导出 export function funName() { return 'you default name is FunName'; } // 导出列表 export { test2, test3 };
三、import和export的扩展
1、export
export 语句用于从模块中导出实时绑定的函数、对象或原始值,以便其他程序可以通过 import 语句使用它们。exports 导出方式:
- 命名导出(每个模块包含任意数量)
- 默认导出(每个模块只能包含一个)
// 导出单个特性 export let name1, name2, …, nameN; // also var, const export let name1 = …, name2 = …, …, nameN; // also var, const export function FunctionName(){...} export class ClassName {...} // 导出列表 export { name1, name2, …, nameN }; // 重命名导出 export { variable1 as name1, variable2 as name2, …, nameN }; // 解构导出并重命名 export const { name1, name2: bar } = o; // 默认导出 export default expression;
2、import
静态的 import 语句用于导入由另一个模块导出的绑定。无论是否声明了 strict mode,导入的模块都运行在严格模式下。
// 导入整个模块的内容 import * as comm from './comm.js'; // 导入单个接口 import {test2} from './comm.js'; // 导入多个接口 import {test2,test3} from './comm.js'; // 重命名接口 import {test2 as newTest,test3} from './comm.js';

浙公网安备 33010602011771号