Skip to Content

代码组件 API 参考

zvm-code-context 为代码组件提供了一些对宿主项目上下文绑定过的 API。开发者可以通过相关 API 更便捷地实现所需功能。

引入方式

import { useAppContext } from 'zvm-code-context'; const ctx = useAppContext();

API 列表

1. navigate (页面跳转)

跳转到宿主项目的指定页面,并可携带参数。推荐使用此方式跳转以执行特定的跳转逻辑。

// 跳转至 /user/123,并携带参数 id=123 ctx.navigate('/user/123', { params: { id: 123 } });

2. query (GraphQL 请求)

向宿主项目的后端发起 GraphQL 请求。

import userListQuery from './graphql/userListQuery.gql'; // 执行查询 const res = await ctx.query(userListQuery.loc.source.body, { page: 1 }); const users = res?.data?.userList;

3. subscribe (订阅数据)

向宿主项目后端发起订阅请求,监听数据变化。

ctx.subscribe( `subscription get_test($where: test_bool_exp!) { test(where: $where, limit: 1) { id name } }`, { where: { id: { _eq: 1 } } }, (data) => { console.log('收到实时更新数据:', data); } );

4. globalData (全局变量)

访问当前宿主环境定义的全局变量(如:当前用户信息、主题配置)。

const theme = ctx.globalData.theme; const currentUser = ctx.globalData.currentUser;

5. pageData (页面变量)

访问当前宿主项目运行页面的页面变量。

const pageVars = ctx.pageData;

6. component (即将废弃)

包含了宿主项目用于描述当前组件实例的所有数据信息。

const componentInfo = ctx.component;

7. discover (即将废弃)

根据组件 ID 获取宿主项目中的特定组件实例。

ctx.discover("component_id");
Last updated on