【问题标题】:How does one access `$global` or `out.global` in non-top-level components in MarkoJS?如何在 MarkoJS 的非顶级组件中访问 `$global` 或 `out.global`?
【发布时间】:2018-04-09 02:55:08
【问题描述】:

我正在尝试从 Marko 组件访问全局变量,但我收到了 Uncaught ReferenceError: out is not defined

class {
    onClick(event) {
        console.log(out.global.message)
        event.preventDefault()
    }
}

out.global/$global 不应该随处可见吗?

【问题讨论】:

    标签: javascript marko


    【解决方案1】:

    out 可用于某些生命周期方法中的组件——onCreate(input, out)onInput(input, out)onRender(out)。在其中之一中,将您想要的值分配给this,以便在课堂上的其他地方访问它:

    class {
        onCreate(input, out) {
            this.message = out.global.message
        }
    
        onClick(event) {
            console.log(this.message)
            event.preventDefault()
        }
    }
    

    对于非顶级组件,状态和属性不会自动序列化,所以上面的代码会导致在服务端的组件中设置this.message,但在客户端该属性是未定义的。

    要使客户端上的out.global.message 对非顶级组件可用,您必须更改渲染函数以指定它应该被序列化,如the docs on server-side rendering

    template.render({
        $global: {
            serializedGlobals: {
                message: true
            }
        }
    }, res);
    

    【讨论】:

    • 如果我不希望我的全局变量被序列化(例如,如果我的变量是函数),我需要在非顶级组件中使用这个全局函数怎么办?跨度>
    猜你喜欢
    • 2021-10-07
    • 1970-01-01
    • 2015-08-27
    • 2010-11-07
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    相关资源
    最近更新 更多