You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AlpineJS中从Proxy获取真实对象?类似Vue的toRaw

AlpineJS 替代 Vue toRaw 的方法:获取 Proxy 背后的原始对象

方法1:使用 Alpine 内置的 Alpine.raw()

AlpineJS v3+ 自带 Alpine.raw() 函数,作用和 Vue 的 toRaw 完全一致,能直接提取响应式 Proxy 对应的原始对象。

修改你的 renderPage 方法:

renderPage() {
    const rawPdf = Alpine.raw(this.pdfInstance);
    // 现在可正常调用 getPage 等方法
    rawPdf.getPage(1).then(page => {
        // 编写页面渲染逻辑
    });
}

方法2:不将 PDF 实例设为响应式数据

如果不需要监听 pdfInstance 的变化,完全可以用非响应式变量存储,避免被 Proxy 包装:

Alpine.data('pdfViewer', () => {
    // 定义非响应式变量,不放在返回的响应式对象中
    let pdfInstance;

    return {
        createPdf() {
            PDFJS.getDocument(option.url).promise.then(pdf_ => {
                pdfInstance = pdf_;
                this.renderPage();
            });
        },
        renderPage() {
            // 直接访问原始实例,无 Proxy 相关报错
            pdfInstance.getPage(1).then(page => {
                // 页面渲染逻辑
            });
        }
    };
});

报错原因

PDF.js 的实例包含 JavaScript 私有字段(以 # 开头),这类字段只能在原始对象的上下文中访问。当实例被 Alpine 的 Proxy 包装后,访问私有字段会触发类型错误,也就是你遇到的 Uncaught (in promise) TypeError: Cannot read from private field。

内容的提问来源于stack exchange,提问作者sohail ahmad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 03:20:10