分类: javascript 4405阅读阅读模式
常见的函数写法,在某个 js 文件中定义方法,在其他组件使用时,先 import 再使用,如下:
func.js 定义了多个函数方法
- function xxx(){
- ...
- }
- function xxx2() {
- ...
- }
- module.exports = {
- xxx,
- xxx2
- }
xxx.vue 中使用
- import {xxx,xxx2} from "xxx.js"
- xxx()
每次用该方法时都需要 import {xxx,xxx2} from "xxx.js"
,无疑带来许多不必要的重复代码。
如果不想这么写,这就需要来定义全局函数。
单个注册
常见的定义是这样的:
在入口 inde.js 文件写:
- Vue.prototype.xxx = function(){
- ...
- }
- Vue.prototype.xxx2 = function(){
- ...
- }
然后在子组件 xxx.vue 中直接调用该方法:
- this.xxx()
- this.xxx2()
这种是一个常见的写法,但是不太适用于多个。
因为太多导致入口文件 index.js 一大堆 function ,导致后期维护艰难,写函数注释也是无从下手。
集中注册
有没有集中放在一个js文件中,然后再进行注册?有的
如:
func.js 中改写成如下函数
- function xxx(){
- ...
- }
- function xxx2() {
- ...
- }
- // 直接挂载
- exports.install = function (Vue,opt) {
- Vue.prototype.xxx = xxx;
- Vue.prototype.xxx2 = xxx2;
- }
入口 index.js 中写:
- import AllFunc from "./func.js";
- Vue.use(AllFunc)
在子组件中直接写
- this.xxx()
- this.xxx2()
引入js框架
额外的,引入其他 js 框架挂载到全局
如引入 weui.js 文件中的函数
那么在 func.js 中添加挂载
- import weui from "weui.js";
- exports.install = function (Vue,opt) {
- Vue.prototype.weui = weui;
- }
在子组件中直接写 weui.js 中的方法:
- this.weui.toast("xxx");
完!
相关评论 当前评论 1 条 [ 游客 1 | 博主 0 ]
评论我看看怎么样