# ctx 上下文

# 变量

# window.inPreview

  • 类型:Boolean
  • 功能说明:判断当前环境是否为编辑/预览环境
  • 值:编辑/预览环境:true, html 环境:false

# ctx.inEditor

  • 类型:Boolean
  • 功能说明:判断当前环境是否为编辑环境
  • 值:编辑环境:true, html/预览环境:false

# ctx.xEditorStore.currentPageId

  • 类型:String
  • 功能说明:获取当前页面 id

# ctx.xEditorStore.formData

  • 类型:Object
  • 功能说明:获取所有表单元素

# ctx.xEditorStore.query

  • 类型:Object
  • 功能说明:url 跳转时需要携带的参数集合

# ctx.project

  • 类型:Object
  • 功能说明:获取当前项目

# ctx.components

  • 类型:Widgets
  • 功能说明:获取当前项目
  • 示例
let widget = ctx.widget;
  let firstLayer = widget.layers[0];
  let Layer = ctx.components.Layer;
  let widgets = firstLayer.widgets;
  if (!widgets || widgets.length == 0) {
    return (
      <div className='widget-container'>
        <div className='widget-container-placeholder'>
          右键进入编辑内容
        </div>
      </div>
    );
  }
  // 取出来第一个layer 作为渲染项目
  return (
    <Layer widgets={widgets} container={firstLayer} />
  );
}

# ctx.widget

  • 类型:Object
  • 功能说明: UI 组件内所有钩子函数上的 ctx 都有 widget 属性,widget 为该 UI 组件所有的属性和方法的集合。
  • 示例
const { widget } = ctx
const { data } = widget

# ctx.trigger

  • 类型:Object
  • 功能说明: 行为组件内所有钩子函数上的 ctx 都有 trigger 属性,trigger 为该 UI 组件所有的属性和方法的集合。
  • 示例
const { trigger } = ctx
const { data } = trigger

# ctx.project

  • 类型: Object
  • 功能说明:获取当前项目配置

# ctx.page

  • 类型: Object
  • 功能说明:获取当前页面配置

# 方法

# H5, 小程序 通用方法

# ctx.getWidget(lookup)

/**
* 根据组件路径获取组件数据
*
* @param {string} lookup 查找组件路径
* @return {Object} 组件数据
*/

// 示例

config: {
    widget: {
      text: '所有组件',
      type: 'WidgetSelect'
    }
}
data: {widget:  ''}
// 获取当前选择的组件
ctx.getWidget(widget)

# ctx.getUrlParmas(window.location.href)

/**
 * 获取url的参数
 *
 * @param {string, string} key, value
 *
 */

// 示例

let urlParmas = ctx.getUrlParmas(window.location.href) // 小程序可以不传值
let sourceId = urlParmas['xeswx_sourceid']

# ctx.setQuery(key, value)

/**
 * 设置需要在url携带的参数
 *
 * @param {string, string} key, value
 *
 */

// 示例

ctx.setQuery('grade', '一年级')

# ctx.setPageData(key, value)

/**
 * 设置页面内变量
 *
 * @param {string, string} key, value
 *
 */

// 示例

ctx.setPageData('isLogin', false)

# ctx.getPageDataByKey(key)

/**
 * 根据变量名称获取变量内容
 *
 * @param {string}key 变量名称
 * @return {string/boolean/number} 变量内容
 */

// 示例

ctx.getPageDataByKey('isLogin')

# ctx.post()

/**
 * post 请求, 同 axios.post
 */

// 示例

ctx
  .post(data.url, data.formData)
  .then((res) => {})

// 如需请求头添加 x-businessLine-id ,
// url 或 params 中追加 `_requireBusinessLineId: true`

ctx
  .post(data.url, {
    ...data.formData, 
    _requireBusinessLineId: true
  })
  .then((res) => {})

# ctx.get()

/**
 * get 请求, 同 axios.get
 */

// 示例

ctx
  .get(data.url, {
    ID: 12345,
  })
  .then((res) => {})

// 如需请求头添加 x-businessLine-id,同 ctx.post
// url 或 params 中追加 `_requireBusinessLineId: true`

ctx
  .get(data.url, {
    ID: 12345,
    _requireBusinessLineId: true
  })
  .then((res) => {})

# ctx.instance()

/**
* 发送异步请求,同 axios(config)

*/

// 示例

ctx
  .instance({
    method: 'post',
    url: '/user/12345',
    data: {
      firstName: 'Fred',
      lastName: 'Flintstone',
    },
  })
  .then((res) => {})

# ctx.instance.interceptors

/**
 * 增加响应拦截器,同 axios(config)
 */

// 示例
ctx.instance.interceptors.response.use(
  (response) => {
    // 只将请求结果的data字段返回(JSON格式处理)
    if (response.code !== 0 && response.msg) {
      ctx.showToast({
        message: response.msg,
        duration: 2000,
      })
    }
    return response
  },
  (err) => {
    // 对响应错误做点什么
    return Promise.reject(err)
  }
)

# ctx.emmit(event)

/**
* 触发事件/触发监听器
* @param {string} event 事件名称

* @param {Option} 监听器对象
*/

// 示例

ctx.emmit('formChange') // 触发事件

ctx.emmit({
  // 触发监听器
  listener: 'changePanel', // 监听器方法名称
  data: { index: index },
})

# ctx.showToast()

/**
 * 弹出Toast
 */

// 示例

ctx.showToast({
  message: '这是一条提示信息',
  duration: 2000,
})

# ctx.jumpToH5()

/**
 * 跳转至其他H5页面
 */

// 示例

ctx.jumpToH5('https://www.xueersi.com')

# ctx.getLoginStatus()

/**
 * @description: 检测用户登录态
 * @param {string}  默认网校接口
 * @return {Object}
 *  data : {
      uid:
      user_info: {
        name:
        phone:
      }
    },
    stat  0未登录, 1登录成功
 */
// 示例
let { stat, data } = await ctx.getLoginStatus()

# ctx.frezzPage()

/**
 * 阻止/允许当前页面滚动
 * @param {Boolean} true 冻结页面, false 解冻页面
 */

// 示例
ctx.frezzPage(true)

# ctx.sendLoadLog(options)

/**
 * 发送展现日志
 * 该函数的参数,用户可以自定义传入,会默认携带eventid:'xesh5' 和 isNewUser
 * isNewUser: 是否是新用户,1:是 2:否
 *@param {Object}展现日志需要携带的参数
 */

ctx.sendLoadLog(options)

# ctx.sendClickLog()

/**
 * 发送交互日志
 * 该函数的参数,用户可以自定义传入,所有传入的参数,都会携带到交互日志中
 *@param {Object}交互日志需要携带的参数
 */

// 示例

ctx.sendClickLog({
  clickid: 'picker',
  value: data.value,
})

# ctx.setLogCommonParams()

/**
 * 设置公共日志参数
 * 用户通过此函数向公共参数中存放新的字段,所有传入的参数,都会携带到交互日志中
 * @param {Object} options 公共日志参数
 */
// 示例
ctx.sendClickLog({
  custom1: 'c1',
  custom2: 'c2',
})

# ctx.getClient()

/**
* 获取客户端

* @return {string} 客户端名称

*/
返回值 客户端
jzh 学而思网校 App
wx 微信
other 其他
wxmini 小程序

# ctx.setCookie(key, value)

/**
 * 新增cookie
 *
 * @param {string}key 变量名称
 * @param {string/number/boolean}value 变量名称
 */

# ctx.getCookie(key)

/**
 * 根据变量名称返回对应cookie内容
 *
 * @param {string}key 变量名称
 * @return {string/boolean/number} 变量内容
 */

# ctx.setShareConfig()

/**
 * 设置分享参数
 *
 * @param {object} options 分享参数
 * @param {string} options.shareTitle 分享标题
 * @param {string} options.shareContent 分享内容
 * @param {string} options.shareUrl 分享链接
 * @param {string} options.shareImgUrl 分享图标
 * @param {string} options.wxMiniPath 小程序分享图片
 * @param {string} options.wxMiniImageUrl 小程序分享路径
 */

# ctx.showAlert(options)

/**
 * @description: 展示弹窗
 * @param {string}  title 提示的标题
 * @param {string}  info 提示的内容
 * @param {string}  btnText  按钮文本
 * @param {function} btnAction 点击按钮回调 
 * @param {boolean} isCustom 是否自定义回调
 */

// 示例
const options = {
  title: '我是一行标题',
  info: '我是一大段文案我是一大段文案我是一大段文',
  btnText: '好的',
}
ctx.showAlert(options)

# ctx.useDataValue(value)

/**
 * 获取页面中的某个变量
 *@param {string} value 变量名称
 */

ctx.useDataValue('title')

# H5 方法

# ctx.getQuery()

/**
 * 获取setQuery设置的所有参数
 */

// 示例

ctx.getQuery()

# ctx.getPageIndex()

/**
 * 获取当前页面的索引
 */

# ctx.goToShare()

/**
 * 触发学而思App原生分享
 * @param {Object} opts 分享链接上额外拼接的参数
 * @param {Object} shareConfig 原生分享配置详细见: https://wiki.zhiyinlou.com/pages/viewpage.action?pageId=31222997
 * @param {function} cb
 */

// 示例

ctx.goToShare(
  {
    uid: 123,
  },
  {
    shareType: 2,
    title: '网校就上学而思',
    imagePath: 'http://activity.xueersi.com/oss/resource/poster-6e135.png',
  },
  (state) => {
    console.log(state, '分享')
  }
)

# ctx.loadScript()

/**
 * 加载外部js文件
 * @param {string} url 加载外部js文件地址
 */

// 示例

ctx.loadScript('https://ocpc.xueersi.com/openinstall.js').then((res) => {
  // do something
})

# ctx.login()

/**
 * @description: 展示登录弹窗:网校客户端下调起 App 登录页,其他环境下 H5 页面弹窗登录
 * @param {string}  successType 固定值 custom
 * @param {function}  success 登录成功后的回调 cb
 * @param {string}  sGroupId  可不传
 */

// 示例

ctx.login({
  successType: 'custom',
  success: () => {
    window.location.reload()
  },
})

# ctx.getPlantform()

/**
 * 获取平台名称
 *@return {string} 平台名称
 */
  • 返回值

    iOS

    android

    other

# ctx.getCookieObj()

/**
 * 获取所有cookie内容
 *
 * @return {Object}
 */

# ctx.delCookie(key)

/**
 * 根据变量名称删除对应cookie内容
 *
 * @param {string}key 变量名称
 */

# 小程序方法

# ctx.navigateToMiniProgram(path, appId)

/**
 * @description: 跳转至其他小程序页面
 * @param {string}  path 小程序路径
 * @param {string}  appId 小程序appId
 */

// 示例
ctx.navigateToMiniProgram(
  'pages/oldNew/newTemplate?p=6125ab80&ruleId=612775ec149007092e4ba682',
  'wxad7477fc4b2c5605'
)

# ctx.setShareData(key, value)

/**
 * 分享链接上添加参数
 *@param {string} key 参数名
 *@param {string} value 参数值
 */

ctx.setShareData('grade', '一年级')

# ctx.changeCurrentPageIndex(pageId)

/**
 * 跳转到当前项目的某个页面
 *@param {string} pageId
 */

ctx.changeCurrentPageIndex('8h4vxyrix7')

# ctx.scrollTo(distance)

/**
 * 将页面滚动到目标位置
 *@param {number} distance 滚动距离
 */

ctx.scrollTo(30)

# 小程序对象

# ctx.lottie

  • 功能说明:在小程序中使用lottie动画库
// 示例

/**
 * canvas 对象用于适配
 */

<canvas id="normal-box" canvasId="cv1" className="box" type="2d"></canvas>

/**
 * 使用 lottie 接口
 */

onMount: async function (ctx) {
  const json = await ctx.get('https://editor.xesimg.com/tailor/resource/Normal-1626503612001.json')
  const { lottie } = ctx
  setTimeout(() => {
    wx.createSelectorQuery()
    .in(ctx.canvasCtx)
    .select('#normal-box')
    .fields({ node: true, size: true })
    .exec(async res => {
      const canvas = res[0].node
      const {w: width, h: height} = json
      const context = canvas.getContext('2d')
      const dpr = wx.getSystemInfoSync().pixelRatio
      const scale = wx.getSystemInfoSync().windowWidth / 375
      canvas.width = width * dpr * scale
      canvas.height = height * dpr * scale
      lottie.setup(canvas)
      lottie.loadAnimation({
        renderer: 'canvas', // 只支持canvas
        loop: true,
        autoplay: true,
        animationData: json,
        rendererSettings: {
          context
        }
      })
    })
  }, 200);
}

# ctx.scoper || ctx.canvasCtx

  • 功能说明:微信小程序中使用canvas时需要使用的上下文对象

# ctx.env

  • 功能说明:环境标识符
  • 值:'sandbox': 沙箱环境; 'production' 线上生产环境;默认为生产

# ctx.userInfo

  • 类型: Object
  • 功能说明:获取用户信息
/**
 *@param {string} userId 用户id
 *@param {string} isNew 是否是新用户 0:未登录 1:是 2:否
 */

# ctx.localStorage

  • 功能说明:localStorage对象,提供get、set、remove操作
  • 值(Object)
localStorage.getItem(attr)
localStorage.setItem(attr, value)
localStorage.removeItem(attr) 

# ctx.commonParams

  • 功能说明:获取小程序公共参数
  • 值(Object)
{
  appid: "wxad7477fc4b2c5605"
  clientId: "114210"
}

# 组件

# ctx.components.Layer

/**
* 面板,UI组件中使用,配置时可以放入其他UI组件
*/
  onRender: function (ctx) {              // eslint-disable-line no-unused-vars
    let Layer = ctx.components.Layer;
    // 获取当前UI组件上所有layer
    let layers = ctx.widget.layers || [];
    // 获取当前UI组件上第一个layer
    let topLayer = layers[0] || {}
    // 获取当前UI组件上第一个layer上的所有UI组件
    let topLayerWidgets = topLayer.widgets || []             // eslint-disable-line no-unused-vars
    return (
      <div>
        <Layer widgets={topLayerWidgets} container={topLayer} />
      </div>
    );