Svelte学习笔记一: 环境搭建和第一个Svelte程序
最近听到组里的大佬谈论起Svelte,打算用下班的时间好好学一学,每天更新,算是给自己学习的一个动力吧。
文档地址:svelte文档地址
1. 项目开始
通过npx拉取项目模板然后开始svelte之旅吧~
npx degit sveltejs/template my-svelte-project
cd my-svelte-project
npm install
npm run dev
2. 什么是Svelte
以下两段话我觉得很重要,反应了svelte的思想,引用一段官方的话
Svelte is a tool for building fast web applications.
It is similar to JavaScript frameworks such as React and Vue, which share a goal of making it easy to build slick interactive user interfaces.
类似于React和Vue的JavaScript框架,用于快速的构建灵活的用户交互。
But there’s a crucial difference: Svelte converts your app into ideal JavaScript at build time, rather than interpreting your application code at run time. This means you don’t pay the performance cost of the framework’s abstractions, and you don’t incur a penalty when your app first loads.
Svelte和其他框架最大的不同点:将app在build时就将其 转换为想要的JavaScript代码,而不是在运行时,意味着你们不需要去关注框架在抽象意义上的性能,以至于在首次加载时不需要去关注性能问题。
You can build your entire app with Svelte, or you can add it incrementally to an existing codebase. You can also ship components as standalone packages that work anywhere, without the overhead of a dependency on a conventional framework.
如何编写一个svelte组件:
In Svelte, an application is composed from one or more components. A component is a reusable self-contained block of code that encapsulates HTML, CSS and JavaScript that belong together, written into a
.svelte
file. The ‘hello world’ example in the code editor is a simple component.在Svelte组件中,每一个组件是由一个HTML,CSS和JavaScript块包裹而成的独立模块,并写入.svelte文件中
3. 第一个Svelte组件
- 代码
// main.js
import App from './App.svelte';
const app = new App({
target: document.body,
});
export default app;
// App.svelte
<script>
let name = 'world';
</script>
<div>hello {name.toUpperCase()}</div>
<style>
div {
color: blue;
font-size: 18px;
line-height: 20px;
font-weight: 500;
}
</style>
- 实现效果
上面这个例子表明几点:
- App组件通过import导入到页面中,通过target传递需要对应挂载到的节点上
- 在.svelte中每个子组件中在script,style标签中分别编写js和css代码
- 在模板html中可以通过单大括号{}来动态绑定数据,且在{}中可以执行js逻辑