在数据或设置函数中声明变量有什么区别?
我是vue.js的新手,正如我所看到的,这两个函数均可用来定义/初始化文件中使用的变量。但是从我的阅读中,我尚不清楚差异是什么,以及我什么时候应该使用哪个来声明/初始化变量。
到目前为止,我只意识到数据功能中声明的变量然后包裹在代理对象中,当我尝试将对象保存在数据库中时,这会引起麻烦。现在,我在想我是否应该继续使用数据功能并在需要保存时从代理中创建一个普通对象,还是应该使用设置功能。
如果不清楚我在说什么:
示例A:
data() {
return {
person: {
age: 5,
name: "Peter"
}
}
}
示例B:
setup() {
return {
person: {
age: 5,
name: "Peter"
}
}
}
I am new to Vue.js and as I see it, both functions can be used to define/initialize variables used in the file. But from what I read, it is not clear to me what the differences are and when I should use which one to declare/initialize variables.
So far I've only realized that variables declared in the data function are then wrapped in a proxy object, which causes troubles when I try to save the object in a database. Now I'm thinking whether I should keep using the data function and create a normal object from the proxy when I need to save it, or whether I should instead just use the setup function.
In case it's not clear what I'm talking about:
Example A:
data() {
return {
person: {
age: 5,
name: "Peter"
}
}
}
Example B:
setup() {
return {
person: {
age: 5,
name: "Peter"
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不同之处在于,data()是vue.js选项API中使用的语法(vue.js 2中的典型方法,该方法在vue.js 3中也有效),setup()sintaxis是组成API的一部分(在vue.js 3中引入)。该组成的API使vue.js组件的JavaScript块更加均匀,可重复使用(除其他优势外)。
https://fjolt.com/article/vue-composition-composition-composition-composition-composition-api-vs-options-api#:~: text = what %%20IS%20%%20 difference%20betpet%20bettheem theempen,like%20in %20%20Options%20API 。
The difference is that data() is the syntax used in the options API of Vue.js (the typical approach in Vue.js 2 which is also valid in Vue.js 3) and the setup() sintaxis is part of the composition API (introduced in Vue.js 3). This composition API makes the JavaScript block of a Vue.js component more uniform and reusable (among other advantages).
https://fjolt.com/article/vue-composition-api-vs-options-api#:~:text=What%20is%20the%20difference%20between,like%20in%20the%20Options%20API.
您可以想到示例A:
但是在示例B中,对象
person
没有被反应性包裹,因此不会观看或反应性。数据 - >设置:
You can think of Example A as:
But in Example B, object
person
didn't wrapped by reactive, so it won't be watched or reactive.A more proper example for data -> setup: