zoukankan      html  css  js  c++  java
  • Vue import、export及export default示例详解,附带如何实现全局调用

    最近在看vue,整理一下vue的知识点,在Vue中,有两种导入导出方式,一个是部分导入导出,一个是全部导入导出,现在做一下简单区别

    一、部分导入导出

    部分导出和部分导入的优势,当资源比较大时建使用部分导出,这样一来使用者可以使用部分导入来减少资源体积,比如element-ui官方的就推荐使用部分导入来减少项目体积,因为element-ui是一个十分庞大的框架,如果我们只用到其中的一部分组件, 那么只将用到的组件导入就可以了。

    1、部分导出的写法

    1 export function helloWorld(){
    2  conselo.log("Hello World");
    3 }
    4 export function test(){
    5  conselo.log("this's test function");
    6 }

    2、部分导入的另一种写法

    1 var helloWorld = function() {
    2  conselo.log("Hello World");
    3 }
    4 var test = function() {
    5  conselo.log("this's test function");
    6 }
    7 export helloWorld;
    8 export test;

    3、部分导入,只需要引入需要的资源

    1 import { helloWorld } from "./utils.js" //只导入utils.js中的helloWorld方法
    2 helloWorld(); //执行utils.js中的helloWorld方法

    4、部分导入,引入全部的资源,比如如果我们需要utils.js中的全部资源则可以全部导入

    1 import * as utils from "./utils.js" //导入全部的资源,utils为别名,在调用时使用
    2 utils.helloWorld(); //执行utils.js中的helloWorld方法
    3 utils.test(); //执行utils.js中的test方法

    二、全部导入导出

    如果使用全部导出,那么使用者在导入时则必须全部导入。

    1、全部导出

     1 var helloWorld=function(){
     2  conselo.log("Hello World");
     3 }
     4 var test=function(){
     5  conselo.log("this's test function");
     6 }
     7 export default {
     8  helloWorld,
     9  test
    10 }

    2、全部导入

    当用export default 导出的时候,随便起一个变量名导入即可

    1 import utils from "./utils.js"
    2 utils.helloWorld();
    3 utils.test();

    备注:

    1、当import 引入依赖包的时候,不需要相对路径,直接引入包名即可,形如:import axios from ‘axios’;

    2、一个js文件中可以有多个export,但只能有一个export default

    三、导入之后,两种调用方式

    1、在当前页面

    在上面的例子中,都是在当前页面调用,直接http.get或http.post就行,在此不再赘述

    2、全局变量

    更多的是全局变量,比如封装的get或post请求方法等

    1 import http from './utils/http';
    2 // 挂载至全局
    3 Vue.prototype.http = http

    引入之后,借助Vue的prototype属性将变量挂载到全局中,这样在任何.vue页面中,直接用this.http.get或this.http.post即可,别忘了this,注意this作用域

    博文参考:

    1、Vue export import 导入导出的多种方式与区别介绍

    2、关于VUE中 import 、 export 和 export default 的注意问题

  • 相关阅读:
    hadoop streaming 中跑python程序,自定义模块的导入
    许久未更新~~重启~~
    什么叫共轭先验或者共轭分布?
    Call for Papers International Conference for Smart Health (ICSH) 2014
    IEEE/ACM International Conference on Advances in Social Network Analysis and Mining (ASONAM) 2014 Industry Track Call for Papers
    linux 查看文件方法
    Double 保留小数点后N位
    java获取当前日期所在的周的周一,并以周一为一周开始
    Core Data Programming Guid
    UIDatePicker应用 常用属性和方法
  • 原文地址:https://www.cnblogs.com/cyfblogs/p/13033717.html
Copyright © 2011-2022 走看看