egg.js中的扩展对象

egg.js扩展对象

在egg中是有五个对象比较常用。

  1. Application
  2. Context
  3. Response
  4. Request
  5. Helper

这五个对象都有相应的作用,也有对应的扩展方法,具体怎么扩展就是要看开发的实际需求

Application的扩展

对这五个对象的扩展,一定要根据相对应的文件里面操作
在这里插入图片描述
这些文件一定要放在app/extend下面。

现在首先来说一下application对象的扩展
文件位置:app/extend/application.js

module.exports = {
  foo(param) {
      console.log(this.config.cluster)  //打印一下端口设置,因为他是application的扩展,所以this就代表了app
  },
};

按照上面的方法来对application进行扩展,而foo函数就会被挂载到app对象上面

调用一下扩展方法

const Controller = require("egg").Controller
class NewsController extends Controller{
    async user_index(){
        //打印一下this,看一下this里面包含着什么
        // console.log(this)
        //调用extend扩展的方法
        this.app.foo();
        this.ctx.body = "你好,小明!";

    }
}

module.exports = NewsController

然后在路由上面匹配这个controller,就可以调用application的方法了

context扩展

首先说明一下文件的路径
app/extend/context.js

module.exports = {
    gethost(){
        // this就代表了ctx
        console.log(this.request.host);
    }
}

在context扩展对象里面this就等于ctx了。这个扩展方法也会同样挂载到context对象上面

然后在controller里面使用这个扩展对象

const Controller = require("egg").Controller
class NewsController extends Controller{
    async user_index(){
        //打印一下this,看一下this里面包含着什么
        // console.log(this)
        //调用context的扩展办法
        this.ctx.gethost();
        this.ctx.body = "你好,小明!";

    }
}

module.exports = NewsController

Response和Request对象扩展

这两个对象的扩展方法的用法是一样的,下面演示一下request

module.exports = {
    foo(param){
        console.log(this.ctx.request);
        return "request"
    }
}

在这里,这些方法会和原先的request对象的方法进行合并和替换。

调用request对象的扩展

const Controller = require("egg").Controller
class NewsController extends Controller{
    async user_index(){
        //打印一下this,看一下this里面包含着什么
        // console.log(this)
        //调用request的扩展方法
        console.log(this.ctx.request.foo());
        this.ctx.body = "你好,小明!";

    }
}

module.exports = NewsController

helper的扩展对象

const sd = require("silly-datetime");
module.exports = {
    //然后这个方法也是可以在模板中使用的
    formtime(param){
    return sd.format(new Date(param*1000),"YYYY-MM-DD HH:mm")
    }
}

在这里使用配件是需要配置的,是需要到config/pulgin.js配置

exports.mssql = {
  enable: true,
  package: "jt-egg-mssql"
};

helper这个对象比较特殊,不但可以在项目应用中使用,也可以在模板渲染中使用

在应用中使用

const Controller = require("egg").Controller
class NewsController extends Controller{
    async user_index(){
        //打印一下this,看一下this里面包含着什么
        // console.log(this)
        //调用hepler的扩展方法
        console.log(this.ctx.helper.formtime("1472952906"))
        this.ctx.body = "你好,小明!";

    }
}

module.exports = NewsController

在模板渲染中使用

<p>使用helper渲染的时间{{helper.formtime("1476364740")}}</p>
扩展方法的用处我觉得是非常大的,可以很好的调整你的项目应用,如果对上面有上面疑问的或者是想一起讨论的可以添加我的QQ 1693490575
发布了28 篇原创文章 · 获赞 14 · 访问量 6786

猜你喜欢

转载自blog.csdn.net/weixin_42304193/article/details/104598366