svelte-cn
svelte-cn copied to clipboard
<script> 翻译较审
<script>
标签里面包含组件实例在创建时时所运行的JavaScript
的代码。
在组件标签顶层显示的声明(导入)变量,有下面四条规则:
1、export
创建组件属性
Svelte
使用export
关键字将变量声明标记为属性
或prop
,这意味着组件的使用者可以直接访问这些变量:
<script>
// these properties can be set externally
export let foo;
export let bar = 'optional default value';
// you can use export { ... as ... } to have
// props whose names are reserved keywords
let clazz;
export { clazz as class };
// this property is readonly externally
export const buzz = 'buzz';
// Values that are passed in as props
// are immediately available
console.log(foo, bar);
// Function expressions can also be props
export let format = (number) => (number.toFixed(2));
// Function declarations are added as methods
// on the component, rather than props
export function greetMethod() {
alert(`I'm a <${this.constructor.name}>!`);
}
// you can also use export { ... as ... } to have
// methods whose names are reserved keywords
function del() {
do_something();
}
export { del as delete };
</script>
2、赋值是响应式
的
要更改组件状态并触发重新渲染,只需给已经声明的变量重新赋值。
更新表达式(count += 1)
和属性赋值(obj.x = y)
具有相同的效果。
由于Svelte
的响应式特性
是基于赋值,因此使用.push()
和.splice()
等数组方法不会自动触发更新。 可以在tutorial中找到解决此问题的方法。
<script>
let count = 0;
function handleClick () {
// calling this function will trigger a re-render
// if the markup references `count`
count = count + 1;
}
</script>
3、$:
标记表达式为响应式
任何顶层语句(即不在块级作用域或函数内)都可以通过在前面添加$:
前缀来使其成为响应式的。 只要它们所依赖的值发生更改,响应式语句就会在组件更新之前立即运行。
<script>
export let title;
// this will update `document.title` whenever
// the `title` prop changes
$: document.title = title;
$: {
console.log(`multiple statements can be combined`);
console.log(`the current title is ${title}`);
}
</script>
如果赋值语句是由完全未声明的变量组成,Svelte
将代表你在语句前面插入let
关键字。
<script>
export let num;
// we don't need to declare `squared` and `cubed`
// — Svelte does it for us
$: squared = num * num;
$: cubed = squared * num;
</script>
4、为 Store 添加$
前缀来访问它们的值
在任何时候,对于任意一个 Store ,你都可以在组件内部为该 Store 的引用添加$
前缀来访问它的值。这会导致Svelte
声明有前缀的变量,并且会设置一个对 Store 的订阅然后在适当的时候取消这个订阅。
要注意的是,Store 必须要在组件的顶层声明 ,并且不可以包含在if
代码块或函数中,例如:
<script>
import { writable } from 'svelte/store';
const count = writable(0);
console.log($count); // logs 0
count.set(1);
console.log($count); // logs 1
</script>
局部变量(不表示存储值)不能有$
前缀。
@tgxpuisb @yuwanli @dujuncheng @daixinye