svelte基础语法学习

2023-12-24 23:58:28

官网文档地址:绑定 / Each 块绑定 ? Svelte 教程 | Svelte 中文网

1、样式

一般情况下父子组件内样式隔离、同级组件间样式隔离

2、页面布局

<style>
  P{
    color: red;
  } 
</stye>

<script>
// 类似data
let name = ‘jiang’
let countVal = 0
let src = ‘https://www.baidu.com’

// 类似methods
let count = () => {
  countVal++
}
</script>


// 直接布局
// 变量使用
<div>{name}</div>
<div on:click={count}>{countVal}</div>
// 属性名和变量名一样可以简写
<img {src} alt=“img” />

3、v-html vs ?@html ??contenteditable=true ?bind:innerHTML

let string = ‘dd <p>dsdsd</p>’
<p>{@html string}</p>

或者
<script>
	let html = '<p>Write some text!</p>';
</script>
<div
	contenteditable="true"
	bind:innerHTML={html}
></div>

4、 methods

<script>
let count = 0;
function handleClick() {
 count += 1;
}
</script>
<button on:click={handleClick}>Clicked {count} {count === 1 ? 'time' : 'times'}</button>

5、computed? vs? $:

这里的computed是由赋值语句触发的,所以变量需要用赋值语句修改值,则computed变量能监听到变化

# 1
<script>
	let count = 0;
    // 定义computed变量
	$: 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>


# 2
当count改变输出log
$: console.log(`the count is ${count}`);


# 3
你可以轻松地将一组语句组合成一个代码块
$: {
	console.log(`the count is ${count}`);
	alert(`I SAID THE COUNT IS ${count}`);
}


# 4
computed里面监听某个data的数据时候,满足一定条件执行相应的逻辑
<script>
	let count = 0;
	$: if (count >= 5) {  类似watch
		alert(`count is dangerously high!`);
		count = 4;
	}
	function handleClick() {
		count += 1;
	}
</script>
<button on:click={handleClick}>
	Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

6、 props 属性 ?vs? export let answer

子组件
<script>
    // props属性
	export let answer;
</script>
<p>The answer is {answer}</p>

父组件
<script>
	import Nested from './Nested.svelte';
</script>
<Nested answer={42}/>

7、v-if? vs? 按条件渲染 {#if 为true变量}…{/if}??? {:else if 条件} {:else? 条件}??? {/if}

<script>
	let user = { loggedIn: false };
	function toggle() {
		user.loggedIn = !user.loggedIn;
	}
</script>
{#if user.loggedIn}
	<button on:click={toggle}>
		Log out
	</button>
{/if}

{#if !user.loggedIn}
	<button on:click={toggle}>
		Log in
	</button>
{/if}


或者
{#if user.loggedIn}
	<button on:click={toggle}>
		Log out
	</button>
{:else}
	<button on:click={toggle}>
		Log in
	</button>
{/if}



多条件渲染
{#if x > 10}
	<p>{x} is greater than 10</p>
{:else if 5 > x}
	<p>{x} is less than 5</p>
{:else}
	<p>{x} is between 5 and 10</p>
{/if}


8、?v-for? vs {#each cats as cat,index}? {#each cats as {name, id},index}?? {/each }

{#each cats as cat, i}
	<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}">
		{i + 1}: {cat.name}
	</a></li>
{/each}

为each块添加key
{#each things as thing (thing.id)}
	<Thing current={thing.color}/>
{/each}

9、事件修饰符 on:click|preventDefault={handleClick}

<script>
	function handleClick() {
		alert('no more alerts')
	}
</script>

<button on:click|preventDefault={handleClick}>
	Click me
</button>

10、$emit? vs createEventDispatcher?? 子组件给父组件传递消息

子组件
<script>
	import { createEventDispatcher } from 'svelte';
	const dispatch = createEventDispatcher();
	function sayHello() { // 给父组件抛出事件
		dispatch('message', {
			text: 'Hello!'
		});
	}
</script>
<button on:click={sayHello}>
	Click to say hello
</button>

注意父组件接收到的信息放在event.detail中
父组件
<script>
	import Inner from './Inner.svelte';
	function handleMessage(event) {
		alert(event.detail.text);
	}
</script>
<Inner on:message={handleMessage}/>

事件转发,可以在中间组件用<Inner on:message/>,默认转发所有message事件

11、表单元素

input??? bind:value

<script>
	let name = 'world';
</script>
<input bind:value={name}>
<h1>Hello {name}!</h1>

<p>{a} + {b} = {a + b}</p>
显示:1+2 = 3

复选框

<input type=checkbox bind:checked={yes}>

绑定更多值 bind:group={flavours}

<script>
	let scoops = 1;
	let flavours = ['Mint choc chip'];

	function join(flavours) {
		if (flavours.length === 1) return flavours[0];
		return `${flavours.slice(0, -1).join(', ')} and ${flavours[flavours.length - 1]}`;
	}
</script>

<h2>Size</h2>

<label>
	<input type=radio group={scoops} value={1}>
	One scoop
</label>

<label>
	<input type=radio group={scoops} value={2}>
	Two scoops
</label>

<label>
	<input type=radio group={scoops} value={3}>
	Three scoops
</label>

<h2>Flavours</h2>

<label>
	<input type=checkbox group={flavours} value="Cookies and cream">
	Cookies and cream
</label>

<label>
	<input type=checkbox group={flavours} value="Mint choc chip">
	Mint choc chip
</label>

<label>
	<input type=checkbox group={flavours} value="Raspberry ripple">
	Raspberry ripple
</label>

{#if flavours.length === 0}
	<p>Please select at least one flavour</p>
{:else if flavours.length > scoops}
	<p>Can't order more flavours than scoops!</p>
{:else}
	<p>
		You ordered {scoops} {scoops === 1 ? 'scoop' : 'scoops'}
		of {join(flavours)}
	</p>
{/if}

12、ref.? vs? bind:this

获取元素或者组件对象

<script>
	import { onMount } from 'svelte';

	let canvas;

	onMount(() => {
        // 挂载之后才会获取到元素
		const ctx = canvas.getContext('2d');
	});
</script>

<style>
	canvas {
		width: 100%;
		height: 100%;
		background-color: #666;
		-webkit-mask: url(svelte-logo-mask.svg) 50% 50% no-repeat;
		mask: url(svelte-logo-mask.svg) 50% 50% no-repeat;
	}
</style>

<canvas
	bind:this={canvas}
	width={32}
	height={32}
></canvas>

13、过渡动画效果 transition

<script>
	import { fade } from 'svelte/transition';
	let visible = true;
</script>

<label>
	<input type="checkbox" bind:checked={visible}>
	visible
</label>

{#if visible}
	<p transition:fade>
		Fades in and out
	</p>
{/if}

上下渐入渐出: fly

<script>
	import { fly } from 'svelte/transition';
	let visible = true;
</script>

<label>
	<input type="checkbox" bind:checked={visible}>
	visible
</label>

{#if visible}
	<p transition:fly="{{ y: 200, duration: 2000 }}">
		Flies in and out
	</p>
{/if}

14、过渡事件

<p
	transition:fly="{{ y: 200, duration: 2000 }}"
	on:introstart="{() => status = 'intro started'}"
	on:outrostart="{() => status = 'outro started'}"
	on:introend="{() => status = 'intro ended'}"
	on:outroend="{() => status = 'outro ended'}"
>
	Flies in and out
</p>

15、组件slots

使用组件不传内容,用默认显示

如果有自定义则显示自定义内容

默认插槽

<slot><p>sdsd</p></slot>

子组件Box.svelte
<div class="box">
	<slot>
		<p>dsdsds</p>
	</slot>
</div>



父组件
<script>
	import Box from './Box.svelte';
</script>

// 显示这里定义的内容
<Box>
	<h2>Hello!</h2>
	<p>This is a box. It can contain anything.</p>
</Box>

// 显示slot默认内容
<Box></Box>

具名插槽

<slot name="address"><p>sdsd</p></slot>

// 子组件
<article class="contact-card">
	<h2>
		<slot name="name">
			<span class="missing">Unknown name</span>
		</slot>
	</h2>

	<div class="address">
		<slot name="address">
			<span class="missing">Unknown address</span>
		</slot>
	</div>

	<div class="email">
		<slot name="email">
			<span class="missing">Unknown email</span>
		</slot>
	</div>
</article>


// 父组件
<ContactCard>
	<span slot="name">
		P. Sherman
	</span>

	<span slot="address">
		42 Wallaby Way<br>
		Sydney
	</span>
</ContactCard>


16、动态组件

<svelte:component this={selected.component}/>
<script>
	import RedThing from './RedThing.svelte';
	import GreenThing from './GreenThing.svelte';
	import BlueThing from './BlueThing.svelte';

	const options = [
		{ color: 'red',   component: RedThing   },
		{ color: 'green', component: GreenThing },
		{ color: 'blue',  component: BlueThing  },
	];

	let selected = options[0];
</script>

<select bind:value={selected}>
	{#each options as option}
		<option value={option}>{option.color}</option>
	{/each}
</select>

<svelte:component this={selected.component}/>

文章来源:https://blog.csdn.net/tangxiujiang/article/details/135187472
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。