Dynamically creating new components does not work in svelte
P粉133321839
P粉133321839 2024-03-31 12:52:32
0
1
497

So I'm trying to create a new component when a button is pressed.

This is where the button is:

<input type="color" id="todo-color" bind:value={todoColor} />
  <input
    type="text"
    id="todo-content"
    placeholder="Todo"
    bind:value={todoContent}
  />
  <input
    type="checkbox"
    name="isImportant"
    id="is-important"
    bind:checked={todoImportance}
  />
  <button on:click={createTodo}>Create todo</button>

The function called is this:

let todoContent: string;
  let todoColor: string = "#ff0000";
  let todoImportance: any = "default";
  const createTodo = () => {
    todoImportance
      ? (todoImportance = "important")
      : (todoImportance = "default");

    console.log(todoColor, todoContent, todoImportance);

    new Task({
      target: document.querySelector('#basic-todos'),
      todoContent,
      todoColor,
      todoImportance,
    });
  };

These three props must be strings, that's what they are. But I always have no definition of these three props.

I have no idea what's wrong with this code at all, if you have a solution or another way to do this I'll take it all :)

P粉133321839
P粉133321839

reply all(1)
P粉763748806

Props as properties props Passed:

new Task({
  target: document.querySelector('#basic-todos'),
  props: {
    todoContent,
    todoColor,
    todoImportance,
  },
});

document

(Assuming these are the correct property names.)

But as mentioned above, this is not how to create a to-do list in Svelte. Data should be added to the list and items should be created declaratively using {#each}.

Approximately as follows:

let items = [];
// ...
const createTodo = () => {
  // [collect/prepare data]

  items = [...items, item];
};
{#each items as { content, color, importance }}
  
{/each}

If items are added/removed in the middle, {#each} requires a key, see documentation.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template