Issue
I tried to declare a variable on a script, but it kept saying that the variable hasn't been declared. This is the code
<head>
<style>
html,body {
margin:0px;
padding:0px;
}
@import url('https://fonts.googleapis.com/css2?family=Roboto&family=Roboto+Condensed:wght@300;400&display=swap');
body{
font-family: 'Roboto', sans-serif;
}
.header{
background-color: #Dcd517;
padding: 5px 5px 5px 20px;
font-size: 16px;
text-align: center;
display: flex;
flex-direction: row;
margin:0px;
}
.header h1{
padding: 0px 8px 0px 0px;
}
.header a{
color: black;
padding:20px;
text-align: center;
width: auto;
border-radius: 12px;
font-size: 32px;
text-decoration:none;
}
.header a:hover{
background-color:#9d940e
}
.cnt1{
display: flex;
background-color:#127D0B;
padding: 8px 50px 8px 50px;
}
.items{
display: flex;
flex-direction: row;
padding: 8px 8px 0px 8px;
}
.items a{
background-color: #1105dc;
color: white;
padding:12px;
mrgin: 8px;
text-align: center;
width: auto;
border-radius: 12px;
font-size: 16px;
text-decoration:none;
}
.items img{
background-color: white;
margin: 8px;
}
</style>
</head>
<body>
<div class = header>
<a href="/"> <b> Pot.Io </b></a>
<a href="/shop"> <b> Shop </b></a>
<a href="/shop"> <b> Help </b></a>
</div>
<script lang="ts">
let items = [
{
name: "test"
},
];
</script>
<div class = cnt1>
{#each items as item}
<div class = item>
<h1>{item.name}</h1>
</div>
{/each}
</div>
</body>
Error code: Cannot find name 'items'. Did you mean 'item'? 'items' is not defined. Consider adding a block with 'export let items' to declare a prop
I tried changing the variable, it did not work. I tried copying it from my previous project. It did not work.
Solution
The script
is within a body tag, thus it will behave like any regular script
element. It has to be at the top level, to become the component's script which can declare variables to be referenced in the markup.
Generally you should not construct a full document in a Svelte component, you can however add things to the head
via <svelte:head>
. You also generally would not add styles directly to the head
and just use a top-level style
element, which scopes the styles to the component.
So the structure of a component usually is the following (order up to preference):
<script>
// props, state & code
</script>
<!-- markup here -->
<style>
/* component styles */
</style>
Answered By - brunnerh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.