VUE JS:反应性语法
当我试图掌握反应性基本面及其语法时,我遇到了以下问题。考虑此片段:
const app = Vue.createApp({
data: dataFunction,
methods: {method1: methodImpl}
})
var dataObj = {
title: 'Holiday',
author: 'Stanley Middleton',
age: 45
}
function dataFunction (){
return dataObj
}
var methodsObj = {
method1: methodImpl
}
function methodImpl (){
this.title = 'Infinite Jest'
}
app.mount('#app')
背后的HTML:
<div id="app">
[...]
<div @click="method1">change book title</div>
</div>
此代码有效,我能够将 data
提取到单独的函数和对象中,但是我该如何使用方法
?
此方法:MethodsObj
不起作用 - 显然。我希望能够在 createApp
初始化中使用我的 methodsobj
。是否可以?
我知道这纯粹是学术的,但是这样的练习可以帮助我了解语法和对象关系。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在javaScript中,
函数。您的代码依赖于提升,这可能是有问题的。
var
var A>,但它们的初始化不是。这是您原始工作代码中提升的可视化:
In JavaScript,
var
s are hoisted, but their initializations are not.function
s and their definitions are also hoisted. Your code relies on hoisting, which can be problematic.Here's a visualization of the hoisting in your original working code:
Now consider that same code, but replace
methods: {method1: methodImpl}
withmethods: methodsObj
:The issue with
methodsObj
in the example above can be fixed by declaring and initializing it before usage (which is generally a best practice):And here's the visualization of the hoisting above:
demo
One of the motivations of
const
andlet
(introduced in ES2015) was to avoid common bugs fromvar
hoisting, such as you observed above. If you had usedconst
/let
instead ofvar
in your original code, the compiler would've thrown an error, which might've signaled to you then that the declaration should be moved above the usage. Consider using a linter that discourages the use ofvar
.