海边的小溪鱼

vuePress-theme-reco 海边的小溪鱼    2017 - 2023
海边的小溪鱼 海边的小溪鱼

Choose mode

  • dark
  • auto
  • light
首页
分类
  • CSS
  • HTTP
  • Axios
  • jQuery
  • NodeJS
  • JavaScript
  • Vue2
  • Server
  • Vue3
标签
时间轴
更多
  • Gitee (opens new window)
Getee (opens new window)
author-avatar

海边的小溪鱼

28

文章

14

标签

首页
分类
  • CSS
  • HTTP
  • Axios
  • jQuery
  • NodeJS
  • JavaScript
  • Vue2
  • Server
  • Vue3
标签
时间轴
更多
  • Gitee (opens new window)
Getee (opens new window)

封装方法(封装通用的函数)

vuePress-theme-reco 海边的小溪鱼    2017 - 2023

封装方法(封装通用的函数)

海边的小溪鱼 2017-07-14 Vue2JavaScript

# export 和 export default 的区别

export 与 export default 的作用: 用于导出常量、函数、文件、模块等

export 的特点
(1). 在一个文件或模块中,可以有多个 export
(2). 导入方式:improt { xxx } from " "
export default 的特点
(1). 在一个文件或模块中,只能有一个 export default
(2). 导入方式:improt xxx from " "

# 封装方法(按需导入的方式)

方式一
1. 新建 src/utils/fn.js 文件

export function add(data) {
    console.log(data);
}

export function sum(num1, num2) {
    console.log(num1 + num2);
}
1
2
3
4
5
6
7

2. 在组件中按需导入

<script>
import { add, sum } from "@/utils/fn.js"
export default {
    created() {
        add(1)
        sum(10, 20)
    }
};
</script>
1
2
3
4
5
6
7
8
9

方式二
1. 新建 src/utils/fn.js 文件

export const fns = {
    add(data) {
        console.log(data);
    },
    sum(num1, num2) {
        console.log(num1 + num2);
    }
}

export const video = {
    list(data) {
        console.log(data);
    }
}

// export { fns, video } // 等同于
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

2. 在组件中按需导入

<script>
import { fns, video } from "@/utils/fn.js"
export default {
    created() {
        fns.add(1)
        fns.sum(10, 20)
        video.list(100)
    }
};
</script>
1
2
3
4
5
6
7
8
9
10

# 封装方法(封装全局公用的方法)

方式一
1. 新建 src/utils/fn.js 文件

const fns = {
    add(data) {
        console.log(data);
    },
    sum(num1, num2) {
        console.log(num1 + num2);
    }
}
export default fns
1
2
3
4
5
6
7
8
9

2. 在 main.js 入口文件中导入

import Vue from 'vue'
import fns from "./utils/fn.js"

Vue.prototype.fns = fns
1
2
3
4

3. 在组件中使用

<script>
export default {
    created() {
        this.fns.add(1)
        this.fns.sum(10, 20)
    }
};
</script>
1
2
3
4
5
6
7
8

方式二
1. 新建 src/utils/fn.js 文件

const article = {
    add(data) {
        console.log(data);
    },
    sum(num1, num2) {
        console.log(num1 + num2);
    }
}

const video = {
    list(data) {
        console.log(data);
    }
}

export default {
    article,
    video
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

2. 在 main.js 入口文件中导入

import Vue from 'vue'
import funcs from "./utils/fn.js"

Vue.prototype.fns = funcs // 绑定到vue原型中并重命名为 fns
1
2
3
4

3. 在组件中使用

<script>
export default {
    created() {
        this.fns.article.add(1)
        this.fns.article.sum(10, 20)
        this.fns.video.list(100)
    }
};
</script>
1
2
3
4
5
6
7
8
9
帮助我们改善此页面! (opens new window)