SVELTE + VITE (二)
SVELTE + VITE (二)
计算属性
<script>
let count = 0;
$: doubled = count * 2;
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
<p>{count} doubled is {doubled}</p>
$:
类似于vue
中的 计算属性。 通常指:组件状态的某些部分需要通过其它部分计算得出。
$:console.log(`the count is $count`)
$:{
console.log(`the count is ${count}`)
alert(`I SAID THE COUNT IS ${count}`)
}
$:if(count>=10){
alert(`count is dangerously high!`);
count = 9;
}
- 不仅可以声明反应式的值,通过可以运行反应式的语句,甚至可以将
$:
放在if
代码块前面
//app.svelte
<script>
let count = 0;
$: if (count >= 10) {
alert(`count is dangerously high!`);
count = 9;
}
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
组件属性传递
//子组件
//Nested.svelte
<script>
export let answer
</script>
<p>
The answer is {answer}
</p>
//父组件
//App.svelte
<script>
import Nested from './Nested.svelte';
</script>
<Nested answer={99} />
- 组件的props ,需要在子组件通过
export
关键字来做到。
//子组件 info.svelte
<script>
export let name;
export let version;
export let speed;
export let website;
</script>
<p>
The <code>{name}</code> package is {speed} fast.
Download version {version} from <a href="https://www.npmjs.com/package/{name}">npm</a>
and <a href={website}>learn more here</a>
</p>
//父组件 App.svelte
<script>
import Info from './Info.svelte';
const pkg = {
name: 'svelte',
version: 3,
speed: 'blazing',
website: 'https://svelte.dev'
};
</script>
<Info {...pkg}/>
- 我们可以通过解构的方式,实现简化。
(....待续)