我正在尝试从 Marko 组件访问全局变量,但我得到了Uncaught ReferenceError: out is not defined
.
class {
onClick(event) {
console.log(out.global.message)
event.preventDefault()
}
}
out.global
/$global
不应该随处可访问吗?
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
在客户端上可用于非顶级组件,必须更改 render 函数以指定应对其进行序列化,如服务器端呈现的文档所示:
template.render({
$global: {
serializedGlobals: {
message: true
}
}
}, res);