svelte是react和vue之外的另一个选择。
创建一个svelte应用很容易:
npx degit sveltejs/template todolist
cd todolist
npm install
npm start dev
它会启动5000端口,打开后,是这样的效果:
为了在vscode里有提示,需要在vscode里安装Svelte for VS Code。
为了有更好的提示,输入一条命令,让它支持typescript:
node scripts/setupTypeScript.js
npm install
npm run dev
这个时候,它已经支持typescript了。
创建srcstores.ts,在这里设置todolist的list:
import { writable } from 'svelte/store';
interface Todo{
done:boolean,
text:string
}
const todo:Todo[]=[
{
done:true,
text:'test-1'
},{
done:false,
text:'test-2'
}
]
export const list_store = writable(todo);
然后,在srcApp.svelte中,导入list:
import { list_store } from './stores.ts';
由于list_store是一个对象,因此还需要再设置一个变量:
let list:Todo[];
并取得值:
const unsubscribe = list_store.subscribe((value) => {
list = value;
});
此时,就可以用循环,把todo给列出来:
{#each list as todo}
<div class:done={todo.done}>
<input type="checkbox" checked={todo.done} />
<input placeholder="What needs to be done?" value={todo.text} />
</div>
{/each}
此刻的效果是:
接下来增加对checkbox的事件处理:
on:change={() => {
todo.done = !todo.done;
}}
同样,还需要对input文本输入进行处理:
on:change={(event) => {
todo.text = event.target.value;
}}
接下来,增加一个添加按钮,和一个删除按钮。
<button
on:click={() => {
list = list.concat({ done: false, text: '' });
}
}>add</button>
<button
on:click={() => {
list = list.filter((todo) => !todo.done);
}}>clear</button>
还要有一个显示状态:
<p>{remaining} remaining</p>
remaining是这样定义的:
$: remaining = list.filter((t) => !t.done).length;
srcApp.svelte全部代码如下:
<script lang="ts">
import { list_store } from "./stores.ts";
interface Todo {
done: boolean;
text: string;
}
let list: Todo[];
const unsubscribe = list_store.subscribe((value) => {
list = value;
});
$: remaining = list.filter((t) => !t.done).length;
</script>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
h1 {
color: #ff3e00;
text-transform: uppercase;
font-size: 4em;
font-weight: 100;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
<main>
<h1>todo list</h1>
{#each list as todo}
<div class:done={todo.done}>
<input
type="checkbox"
checked={todo.done}
on:change={() => {
todo.done = !todo.done;
console.log(todo.done);
}} />
<input
on:change={(event) => {
todo.text = event.target.value;
}}
placeholder="What needs to be done?"
value={todo.text} />
</div>
{/each}
<p>{remaining} remaining</p>
<button
on:click={() => {
list = list.concat({ done: false, text: '' });
}}>add</button>
<button
on:click={() => {
list = list.filter((todo) => !todo.done);
}}>clear</button>
</main>
效果如下:
如果为了UI好看一些,还可以使用svelte-material-ui:
npm install --save-dev svelte-material-ui
npm i -D rollup-plugin-postcss node-sass
mkdir src/theme
touch src/theme/_smui-theme.scss
然后,更改rollup.config.js文件:
新增:
import postcss from "rollup-plugin-postcss";
找到:
commonjs(),
回车,增加如下内容:
postcss({
extract: true,
minimize: true,
use: [
['sass', {
includePaths: [
'./src/theme',
'./node_modules'
]
}]
]
}),
最后,全部代码位于:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。