Svelte | Adding data and working with variables
Last Updated :
29 Oct, 2022
Svelte is a rapid tool for building and developing web applications, it has the upper hand compared to React and Vue because unlike these frameworks svelte converts the app into vanilla javascript during build time. Whereas react and Vue interpret the code during runtime which consumes processing power during runtime because of interpretation.
Pre-requisite: One needs to be familiar with the following technologies before getting into svelte.
- HTML
- CSS
- JavaScript
- Linux
NOTE: If you don’t have svelte installed on your system please follow the instructions given at: https://www.geeksforgeeks.org/svelte-introduction-and-installation/
Components: In svelte a web application is built up from components, a component is nothing but encapsulated, reusable block of code which wraps up HTML, CSS, and JS into a single file <filename>.svelte
Adding data and working with variables: First of all, create an App.svelte file and use the following code example to clear your concepts.
Syntax:
let <varname> ='value';
Parameters:
- <varname> : use any identifier name as per your choice.
- value: use any type of data num, char or string, etc.
Example 1: Here in this example, we will use variables to store text content and color value and we are going to invoke a function to change the values of variables
Javascript
<script>
let name = 'geeksforgeeks' ;
let col = '#0000FF' ;
let c = 0, c1 = 0;
function handle() {
if (c === 0) {
name = name.toUpperCase();
c++;
}
else {
name = name.toLowerCase();
c--;
}
}
function color_handler() {
if (c1 === 0) {
col = '#00FF00' ;
c1++;
}
else {
col = '#0000FF' ;
c1--;
}
}
</script>
<h1 style=color:{col};>Welcome to >> {name}</h1>
<button on:click={handle}>
Change_case
</button>
<button on:click={color_handler}>
color change
</button>
|
Output:
Example 2: Here in this example we are going to use variables to control the content in the <dialog> element and change its attributes dynamically.
Javascript
<script>
let name = 'Welcome to GeeksforGeeks' ;
let msg = "message" ;
let col = '#0000FF' ;
let bg = '#0000FF' ;
let back = '#D3D3D3' ;
function change_n() {
msg = "Hello Nerd!!!" ;
bg = '#0000FF' ;
}
function change_g() {
msg = "Welcome to GeeksforGeeks" ;
bg = '#00FF00' ;
}
</script>
<body style=background-color:{back};>
<h1 style=color:{col};>SVELTE:</h1>
<dialog open style=color:{bg};>{msg}</dialog>
<button on:click={change_n}>
nerd
</button>
<button on:click={change_g}>
geek
</button>
</body>
|
Output:
Reference: https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props
Share your thoughts in the comments
Please Login to comment...