在SvelteKit中,+page.js、+page.server.js和+page.svelte之间有什么区别?

huangapple go评论77阅读模式
英文:

In SvelteKit, what's the difference between +page.js, +page.server.js and +page.svelte?

问题

我无法理解文档中的内容。

假设

  • +page.server.js = 运行于服务器端的代码(从数据库中获取数据等)。
  • +page.js = 在客户端运行的代码(浏览器中的动态内容)。
  • +page.svelte = 主要的前端页面。

作为具体示例,我在布局中有一个data.user.startdate的prop,我想要操作它以显示现在与开始日期之间的差异。

+page.svelte在这里可以轻松访问它:

<script>
 export let data;
</script>

而且我可以在这里操纵数据,但我假设最佳实践应该在 +page.js 中进行操作。

但是 +page.js 似乎没有等效的方法来访问数据prop,除非通过某种父级继承,这与 +page.svelte 相比显得混乱。

我相信主要问题可能是我对sveltekit文件目的的理解,因此问题涉及框架文件。

作为一个旁注,为什么有 + 符号,以及在VS Code中搜索文件的最佳实践是什么,因为所有路由文件都是相同命名!

英文:

I can't make sense of the docs on this at all.

I'm assuming:

  • +page.server.js = code that runs server side (fetching data from db etc.)
  • +page.js = code that runs client side (dynamic stuff in the browser)
  • +page.svelte = the main front end.

As a specific example, I have a data.user.startdate prop in my layout that I want to manipulate so I can display the difference between now and start date.

+page.svelte can access this no problem here:

<script>
 export let data;
</script>

And I could just manipulate the data here, however I'm assuming best practice would be to do this in +page.js

But +page.js seemingly have no equivalent way to access the data prop, without some sort of parent inherit, which is messy compared to +page.svelte

I believe the main issue is likely my understanding of the purpose of the sveltekit files, hence the question is about the framework files.

As a side note, why the + signs, and what's best practice in searching files in VS Code, as all route files are named the same!

答案1

得分: 1

+ 用于标记由 SvelteKit 保留的文件,以回答为什么选择 +,原因与为命令选择 / 一样,只是因为它们需要在名称开头使用一些不常见的符号。

+page.server.js 以下文件在服务器上运行,因此用于从某个需要 API 密钥的 API 获取数据,然后将数据发送到客户端,这样你的 API 密钥不会暴露给客户端。

+page.js 只是一个用于页面上的 JavaScript 文件,因此您可能希望将一些具有大量逻辑并且有点过大的函数移到其中。(因此,您很可能不会为每个页面都有这个文件)

+page.svelte 是您的前端部分,包括 HTML、样式和 JavaScript。

英文:

+ is used to mark files reserved by svelteKit to answer why + specifically for the same reason why / is used for commands just because they needed to use some uncommon symbole in the beginning of the name.

+page.server.js The following file is run on the server so it is used to fetch data from some API which requires an API key and then you just send the data to the client, that way your API key wouldn't be exposed to the client.

+page.js is just a file where you can have js for the page, so you might want to move some function that has a lot of logic and is a bit too big in there. (So you will most likely not have this file for every page)

+page.svelte is where your frontend is, so your HTML styles and js.

huangapple
  • 本文由 发表于 2023年5月14日 02:38:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76244344.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定