import在vue中使用

目录

一、vue中使用import导入的方法

1.需要在methods中申明引入的方法,或通过自定义方法返回

二、import和export的扩展

export

import


一、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>

comm.js示例

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的扩展

export

export 语句用于从模块中导出实时绑定的函数、对象或原始值,以便其他程序可以通过 import 语句使用它们。

exports 导出方式:

  1. 命名导出(每个模块包含任意数量)
  2. 默认导出(每个模块只能包含一个)
// 导出单个特性
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;

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';

猜你喜欢

转载自blog.csdn.net/lqh4188/article/details/125511928