就业培训     下载中心     Wiki     联络
登录   注册

Log
  1. 首页
  2. 学习 Web 开发
  3. Tools and testing
  4. 理解客户端侧 JavaScript 框架
  5. Dynamic behavior in Svelte: working with variables and props

内容表

  • Code along with us
  • Working with todos
  • Dynamically generating the todos from the data
  • Working with props
  • Toggling and removing todos
  • Reactive todos
  • Adding new todos
  • Giving each todo a unique ID
  • Filtering todos by status
  • The code so far
  • 摘要
  • In this module

Dynamic behavior in Svelte: working with variables and props

  • 上一
  • Overview: Client-side JavaScript frameworks
  • 下一

Now that we have our markup and styles ready we can start developing the required features for our Svelte To-Do list app. In this article we'll be using variables and props to make our app dynamic, allowing us to add and delete todos, mark them as complete, and filter them by status.

Prerequisites: At minimum, it is recommended that you are familiar with the core HTML , CSS ,和 JavaScript languages, and have knowledge of the terminal/command line .

You'll need a terminal with node + npm installed to compile and build your app.

Objective: Learn and put into practice some basic Svelte concepts, like creating components, passing data using props, render JavaScript expressions into our markup, modify the components state and iterating over lists.

Code along with us

Git

Clone the github repo (if you haven't already done it) with:

git clone https://github.com/opensas/mdn-svelte-tutorial.git

								

Then to get to the current app state, run

cd mdn-svelte-tutorial/03-adding-dynamic-behavior

								

Or directly download the folder's content:

npx degit opensas/mdn-svelte-tutorial/03-adding-dynamic-behavior

								

Remember to run npm install && npm run dev to start your app in development mode.

REPL

To code along with us using the REPL, start at

https://svelte.dev/repl/c862d964d48d473ca63ab91709a0a5a0?version=3.23.2

Working with todos

我们的 Todos.svelte component is currently just displaying static markup; let's start making it a bit more dynamic. We'll take the tasks information from the markup and store it in a todos array. We'll also create two variables to keep track of the total number of tasks and the completed tasks.

The state of our component will be represented by these three top-level variables.

  1. 创建 <script> section at the top of src/components/Todos.svelte and give it some content, as follows:
    <script>
      let todos = [
        { id: 1, name: 'Create a Svelte starter app', completed: true },
        { id: 2, name: 'Create your first component', completed: true },
        { id: 3, name: 'Complete the rest of the tutorial', completed: false }
      ]
      let totalTodos = todos.length
      let completedTodos = todos.filter(todo => todo.completed).length
    </script>
    
    										
    Now let's do something with that information.
  2. Let's start by showing a status message. Find the <h2> heading with an id of list-heading and replace the hardcoded number of active and completed tasks with dynamic expressions:
    <h2 id="list-heading">{completedTodos} out of {totalTodos} items completed</h2>
    
    										
  3. Go to the app, and you should see the "2 out of 3 items completed" message as before, but this time the information is coming from the todos 数组。
  4. To prove it, go to that array, and try changing some of the todo object's completed property values, and even add a new todo object. Observe how the numbers in the message are updated appropriately.

Dynamically generating the todos from the data

At the moment, our displayed todo items are all static. We want to iterate over each item in our todos array and render the markup for each task, so let's do that now.

HTML doesn't have a way of expressing logic — like conditionals and loops. Svelte does. In this case we use the {#each...} directive to iterate over the todos array. The second parameter, if provided, will contain the index of the current item. Also, a key expression can be provided, which will uniquely identify each item. Svelte will use it to diff the list when data changes, rather than adding or removing items at the end, and it's a good practice to always specify one. Finally, an :else block can be provided, which will be rendered when the list is empty.

Let's give it a try.

  1. Replace the existing <ul> element with the following simplified version to get an idea of how it works:
    <ul>
    {#each todos as todo, index (todo.id)}
      <li>
        <input type="checkbox" checked={todo.completed}/> {index}. {todo.name} (id: {todo.id})
      </li>
    {:else}
      Nothing to do here!
    {/each}
    </ul>
    
    										
  2. Go back to the app; you'll see something like this: very simple todo list output created using an each block
  3. Now we've seen that this is working, let's generate a complete todo item with each loop of the {#each} directive, and inside embed the information from the todos array: id , 名称 ,和 completed . Replace your existing <ul> block with the following:
    <!-- Todos -->
    <ul role="list" class="todo-list stack-large" aria-labelledby="list-heading">
      {#each todos as todo (todo.id)}
        <li class="todo">
          <div class="stack-small">
            <div class="c-cb">
              <input type="checkbox" id="todo-{todo.id}" checked={todo.completed}/>
              <label for="todo-{todo.id}" class="todo-label">
                {todo.name}
              </label>
            </div>
            <div class="btn-group">
              <button type="button" class="btn">
                Edit <span class="visually-hidden">{todo.name}</span>
              </button>
              <button type="button" class="btn btn__danger">
                Delete <span class="visually-hidden">{todo.name}</span>
              </button>
            </div>
          </div>
        </li>
      {:else}
        <li>Nothing to do here!</li>
      {/each}
    </ul>
    
    										
    Notice how we are using curly braces to embed JavaScript expressions in HTML attributes, like we did with the checked and id attributes of the checkbox.

We've turned our static markup into a dynamic template ready to display the tasks from our component's state. Great! We are getting there.

Working with props

With a hardcoded list of todos, our Todos component is not very useful. To turn our component into a general purpose To-Do editor we should allow the parent of this component to pass in the list of todos to edit. This would allow us to save them to a web service or local storage and later retrieve them for update. So let's turn the array into a prop .

  1. 在 Todos.svelte , replace the existing let todos = ...   block with export let todos = [] .
    export let todos = []
    
    										
    This may feel a little weird at first. That's not how export normally works in JavaScript modules! This is how Svelte 'extends' JavaScript by taking valid syntax and giving it a new purpose. In this case Svelte is using the export keyword to mark a variable declaration as a property or prop, which means it becomes accessible to consumers of the component. You can also specify a default initial value for a prop. This will be used if the component's consumer doesn't specify the prop on the component — or if its initial value is undefined — when instantiating the component. So with export let todos = [] , we are telling Svelte that our Todos.svelte component will accept a todos attribute, which when omitted will be initialized to an empty array.
  2. Have a look at the app, and you'll see the "Nothing to do here!" message. This is because we are currently not passing any value into it from App.svelte , so it's using the default value.
  3. Now let's move our todos to App.svelte and pass them to the Todos.svelte component as a prop. Update src/App.svelte 如下:
    <script>
      import Todos from './components/Todos.svelte'
      let todos = [
        { id: 1, name: 'Create a Svelte starter app', completed: true },
        { id: 2, name: 'Create your first component', completed: true },
        { id: 3, name: 'Complete the rest of the tutorial', completed: false }
      ]
    </script>
    <Todos todos={todos} />
    
    										
  4. When the attribute and the variable have the same name, Svelte allows you to just specify the variable as a handy shortcut, so we can rewrite our last line like this. Try this now.
    <Todos {todos} />
    
    										

At this point your todos should render just like they did before, except that now we're passing them in from the App.svelte 组件。

Toggling and removing todos

Let's add some functionality to toggle the task status. Svelte has the on:eventname directive for listening to DOM events. Let's add a handler to the on:click event of the checkbox input to toggle the completed value.

  1. 更新 <input type="checkbox"> element inside src/components/Todos.svelte 如下:
    <input type="checkbox" id="todo-{todo.id}"
      on:click={() => todo.completed = !todo.completed}
      checked={todo.completed}
    />
    
    										
  2. Next we'll add a function to remove a todo from our todos array. At the bottom of the Todos.svelte <script> section, add the removeTodo() function like so:
    function removeTodo(todo) {
      todos = todos.filter(t => t.id !== todo.id)
    }
    
    										
  3. We'll call it via the 删除 button. Update it with a click event, like so:
    <button type="button" class="btn btn__danger"
      on:click={() => removeTodo(todo)}
    >
      Delete <span class="visually-hidden">{todo.name}</span>
    </button>
    
    										
    A very common mistake with handlers in Svelte is to pass the result of executing a function as a handler, instead of passing the function. For example, if you specify on:click={removeTodo(todo)} , it will execute removeTodo(todo) and the result will be passed as a handler, which is not what we had in mind. In this case you have to specify on:click={() => removeTodo(todo)} as the handler. If removeTodo() received no params, you could use on:event={removeTodo} , but not on:event={removeTodo()} . This is not some special Svelte syntax — here we are just using regular JavaScript 箭头函数 .

Again, this is good progress — at this point, we can now delete tasks. When a todo item's 删除 button is pressed, the relevant todo is removed from the todos array, and the UI updates to no longer show it. In addition, we can now check the checkboxes, and the completed status of the relevant todos will now update in the todos array.

However, the "x out of y items completed" heading is not being updated. Read on to find out why this is happening and how we can solve it.

Reactive todos

As we've already seen, every time the value of a component top-level variable is modified Svelte knows how to update the UI. In our app, the todos array value is updated directly every time a todo is toggled or deleted, and so Svelte will update the DOM automatically.

The same is not true for totalTodos and completedTodos , however. In the following code they are assigned a value when the component is instantiated and the script is executed, but after that, their values are not modified:

let totalTodos = todos.length
let completedTodos = todos.filter(todo => todo.completed).length

								

We could recalculate them after toggling and removing todos, but there's an easier way to do it.

We can tell Svelte that we want our totalTodos and completedTodos variables to be reactive by prefixing them with $: . Svelte will generate the code to automatically update them whenever data they depend on is changed.

注意: Svelte uses the $: JavaScript label statement syntax to mark reactive statements. Just like the export keyword being used to declare props, this may look a little alien. This is another example in which Svelte takes advantage of valid JavaScript syntax and gives it a new purpose — in this case to mean "re-run this code whenever any of the referenced values change". Once you get used to it, there's no going back.

Update your totalTodos and completedTodos variable definitions inside src/components/Todos.svelte to look like so:

$: totalTodos = todos.length
$: completedTodos = todos.filter(todo => todo.completed).length

								

If you check your app now, you'll see that the heading's numbers are updated when todos are completed or deleted. Nice!

Behind the scenes the Svelte compiler will parse and analyze our code to make a dependency tree, then it will generate the JavaScript code to re-evaluate each reactive statement whenever one of their dependencies is updated. Reactivity in Svelte is implemented in a very lightweight and performant way, without using listeners, setters, getters, or any other complex mechanism.

Adding new todos

Now onto the next major task for this article — let's add some functionality for adding new todos.

  1. First, we'll create a variable to hold the text of the new todo. Add this declaration to the <script> section of Todos.svelte 文件:
    let newTodoName = ''
    
    										
  2. Now we will use this value in the <input> for adding new tasks. To do that we need to bind our newTodoName variable to the todo-0 input, so that the newTodoName variable value stays in sync with the input's value property. We could do something like this:
    <input value={newTodoName} on:keydown={(e) => newTodoName = e.target.value} />
    
    										
    Whenever the value of the variable newTodoName changes, it will be reflected in the value attribute of the input, and whenever a key is pressed in the input, we will update the contents of the variable newTodoName . This is a manual implementation of two-way data binding for an input box. But we don't need to do this — Svelte provides an easier way to bind any property to a variable, using the bind:property directive:
    <input bind:value={newTodoName} />
    
    										
    So, let's implement this. Update the todo-0 input like so:
    <input bind:value={newTodoName} type="text" id="todo-0" autocomplete="off" class="input input__lg" />
    
    										
  3. An easy way to test that this works is to add a reactive statement to log the contents of newTodoName . Add this snippet at the end of the <script> section:
    $: console.log('newTodoName: ', newTodoName)
    
    										

    注意: As you may have noticed, reactive statements aren't limited to variable declarations. You can put any JavaScript statement after the $: sign.

  4. Now try going back to localhost:5042 , pressing Ctrl + Shift + K to open your browser console and typing something into the input field. You should see your entries logged. At this point, you can delete the reactive console.log() if you wish.
  5. Next up we'll create a function to add the new todo — addTodo() — which will push a new todo object onto the todos array. Add this to the bottom of your <script> block inside src/components/Todos.svelte :
    function addTodo() {
      todos.push({ id: 999, name: newTodoName, completed: false })
      newTodoName = ''
    }
    
    										

    注意: For the moment we are just assigning the same id to every todo, but don't worry, we will fix that soon.

  6. Now we want to update our HTML so that we call addTodo() whenever the form is submitted. Update the NewTodo form's opening tag like so:
    <form on:submit|preventDefault={addTodo}>
    
    										
    on:eventname directive supports adding modifiers to the DOM event with the | character. In this case, the preventDefault modifier tells Svelte to generate the code to call event.preventDefault() before running the handler. Explore the previous link to see what other modifiers are available.
  7. If you try adding new todos at this point, the new todos are added to the todos array but our UI is not updated. Remember that in Svelte reactivity is triggered with assignments . That means that the addTodo() function is executed, the element is added to the todos array, but Svelte won't detect that the push method modified the array, so it won't refresh the tasks <ul> . Just adding todos = todos to the end of the addTodo() function would solve the problem, but it seems strange to have to include that at the end of the function. Instead, we'll take out the push() method and use spread syntax to achieve the same result — we'll assign a value to the todos array equal to the todos array plus the new object.

    注意: Array has several mutable operations — push() , pop() , splice() , shift() , unshift() , reverse() ,和 sort() . Using them often causes side effects and bugs that are hard to track. By using the spread syntax instead of push() we avoid mutating the array, which is considered a good practice.

    Update your addTodo() function like so:
    function addTodo() {
      todos = [...todos, { id: 999, name: newTodoName, completed: false }]
      newTodoName = ''
    }
    
    									

Giving each todo a unique ID

If you try to add new todos in your app now, you'll be able to add a new todo and have it appear in the UI! Once. If you try it a second time, it won't work, and you'll get a console message saying "Error: Cannot have duplicate keys in a keyed each". We need unique IDs for our todos!

  1. Let's declare a newTodoId variable calculated from the number of todos plus 1, and make it reactive. Add the following snippet to the <script> section:
    let newTodoId
      $: {
        if (totalTodos === 0) {
          newTodoId = 1;
        } else {
          newTodoId = Math.max(...todos.map(t => t.id)) + 1;
        }
      }
    
    									

    注意: As you can see, reactive statements are not limited to one-liners. The following would work too, but it is a little less readable: $: newTodoId = totalTodos ? Math.max(...todos.map(t => t.id)) + 1 : 1

  2. How does Svelte achieve this? The compiler parses the whole reactive statement, and detects that it depends on the totalTodos variable and the todos array. So whenever either of them is modified, this code is re-evaluated, updating newTodoId accordingly. Let's use this in our addTodo() function — update it like so:
    function addTodo() {
      todos = [...todos, { id: newTodoId, name: newTodoName, completed: false }]
      newTodoName = ''
    }
    
    									

Filtering todos by status

Finally for this article, let's implement the ability to filter our todos by status. We'll create a variable to hold the current filter, and a helper function that will return the filtered todos.

  1. At the bottom of our <script> section add the following:
    let filter = 'all'
      const filterTodos = (filter, todos) =>
        filter === 'active' ? todos.filter(t => !t.completed) :
        filter === 'completed' ? todos.filter(t => t.completed) :
        todos
    
    									
    使用 filter variable to control the active filter: all , active ,或 completed . Just assigning one of these values to the filter variable will activate the filter and update the list of todos. Let's see how to achieve this. filterTodos() function will receive the current filter and the list of todos, and return a new array of todos filtered accordingly.
  2. Let's update the filter button markup to make it dynamic and update the current filter when the user presses one of the filter buttons. Update it like this:
    <div class="filters btn-group stack-exception">
      <button class="btn toggle-btn" class:btn__primary={filter === 'all'} aria-pressed={filter === 'all'} on:click={()=> filter = 'all'} >
        <span class="visually-hidden">Show</span>
        <span>All</span>
        <span class="visually-hidden">tasks</span>
      </button>
      <button class="btn toggle-btn" class:btn__primary={filter === 'active'} aria-pressed={filter === 'active'} on:click={()=> filter = 'active'} >
        <span class="visually-hidden">Show</span>
        <span>Active</span>
        <span class="visually-hidden">tasks</span>
      </button>
      <button class="btn toggle-btn" class:btn__primary={filter === 'completed'} aria-pressed={filter === 'completed'} on:click={()=> filter = 'completed'} >
        <span class="visually-hidden">Show</span>
        <span>Completed</span>
        <span class="visually-hidden">tasks</span>
      </button>
    </div>
    
    									
    There are a couple of things going on in this markup. We will show the current filter by applying the btn__primary class to the active filter button. To conditionally apply style classes to an element we use the class:name={value} directive. If the value expression evaluates to truthy, the class name will be applied. You can add many of these directives, with different conditions, to the same element. So when we issue class:btn__primary={filter === 'all'} , Svelte will apply the btn__primary class if filter equals all.

    注意: Svelte provides a shortcut which allows us to shorten <div class:active={active}> to <div class:active> when the class matches the variable name.

    Something similar happens with aria-pressed={filter === 'all'} — when the JavaScript expression passed between curly braces evaluates to a truthy value, the aria-pressed attribute will be added to the button. Whenever we click on a button we update the filter variable by issuing on:click={()=> filter = 'all'} . Read on to find out how Svelte reactivity will take care of the rest.
  3. Now we just need to use the helper function in the {#each} loop; update it like this:
    ...
      <ul role="list" class="todo-list stack-large" aria-labelledby="list-heading">
      {#each filterTodos(filter, todos) as todo (todo.id)}
    ...
    
    								
    After analyzing our code, Svelte detects that our filterTodos() function depends on the variables filter and todos . And, just like with any other dynamic expression embedded in the markup, whenever any of these dependencies change the DOM will be updated accordingly. So whenever filter or todos changes, the filterTodos() function will be re-evaluated and the items inside the loop will be updated.

注意: Reactivity can be tricky sometimes. Svelte recognizes filter as a dependency because we are referencing it in the filterTodos(filter, todo) 表达式。 filter is a top-level variable, so we might be tempted to remove it from the helper function params, and just call it like this — filterTodos(todo) . This would work, but now Svelte has no way to find out that {#each filterTodos(todos)... } depends on filter , and the list of filtered todos won't be updated when the filter changes. Always remember that Svelte analyzes our code to find out dependencies, so it's better to be explicit about it and not rely on the visibility of top-level variables. Besides, it's a good practice to make our code clear and explicit about what information it is using.

The code so far

Git

To see the state of the code as it should be at the end of this article, access your copy of our repo like this:

cd mdn-svelte-tutorial/04-componentizing-our-app

						

Or directly download the folder's content:

npx degit opensas/mdn-svelte-tutorial/04-componentizing-our-app

						

Remember to run npm install && npm run dev to start your app in development mode.

REPL

To see the current state of the code in a REPL, visit:

https://svelte.dev/repl/99b9eb228b404a2f8c8959b22c0a40d3?version=3.23.2

摘要

That will do for now! In this article we already implemented most of our desired functionality. Our app can display, add, and delete todos, toggle their completed status, show how many of them are completed and apply filters.

To recap, we covered the following topics:

  • Creating and using components.
  • Turning static markup into a live template.
  • Embedding JavaScript expressions in our markup.
  • Iterating over lists using the {#each} 指令。
  • Passing information between components with props.
  • Listening to DOM events.
  • Declaring reactive statements.
  • Basic debugging with console.log() and reactive statements.
  • Binding HTML properties with the bind:property 指令。
  • Triggering reactivity with assignments.
  • Using reactive expressions to filter data
  • Explicitly defining our reactive dependencies

In the next article we will add further functionality, which will allow users to edit todos.

  • 上一
  • Overview: Client-side JavaScript frameworks
  • 下一

In this module

  • Introduction to client-side frameworks
  • Framework main features
  • React
    • Getting started with React
    • Beginning our React todo list
    • Componentizing our React app
    • React interactivity: Events and state
    • React interactivity: Editing, filtering, conditional rendering
    • Accessibility in React
    • React resources
  • Ember
    • Getting started with Ember
    • Ember app structure and componentization
    • Ember interactivity: Events, classes and state
    • Ember Interactivity: Footer functionality, conditional rendering
    • Routing in Ember
    • Ember resources and troubleshooting
  • Vue
    • Getting started with Vue
    • Creating our first Vue component
    • Rendering a list of Vue components
    • Adding a new todo form: Vue events, methods, and models
    • Styling Vue components with CSS
    • Using Vue computed properties
    • Vue conditional rendering: editing existing todos
    • Focus management with Vue refs
    • Vue resources
  • Svelte
    • Getting started with Svelte
    • Starting our Svelte Todo list app
    • Dynamic behavior in Svelte: working with variables and props
    • Componentizing our Svelte app
    • Advanced Svelte: Reactivity, lifecycle, accessibility
    • Working with Svelte stores
    • TypeScript support in Svelte
    • Deployment and next steps
  • Angular
    • Getting started with Angular
    • Beginning our Angular todo list app
    • Styling our Angular app
    • Creating an item component
    • Filtering our to-do items
    • Building Angular applications and further resources

发现此页面有问题吗?

  • 编辑在 GitHub
  • 源在 GitHub
  • Report a problem with this content on GitHub
  • 想要自己修复问题吗?见 我们的贡献指南 .

最后修改: Jan 11, 2022 , 由 MDN 贡献者

相关话题

  1. Complete beginners start here!
  2. Web 快速入门
    1. Getting started with the Web overview
    2. 安装基本软件
    3. What will your website look like?
    4. 处理文件
    5. HTML 基础
    6. CSS 基础
    7. JavaScript 基础
    8. 发布您的网站
    9. How the Web works
  3. HTML — Structuring the Web
  4. HTML 介绍
    1. Introduction to HTML overview
    2. Getting started with HTML
    3. What's in the head? Metadata in HTML
    4. HTML text fundamentals
    5. Creating hyperlinks
    6. Advanced text formatting
    7. Document and website structure
    8. Debugging HTML
    9. Assessment: Marking up a letter
    10. Assessment: Structuring a page of content
  5. 多媒体和嵌入
    1. Multimedia and embedding overview
    2. Images in HTML
    3. Video and audio content
    4. From object to iframe — other embedding technologies
    5. Adding vector graphics to the Web
    6. Responsive images
    7. Assessment: Mozilla splash page
  6. HTML 表格
    1. HTML tables overview
    2. HTML table basics
    3. HTML Table advanced features and accessibility
    4. Assessment: Structuring planet data
  7. CSS — Styling the Web
  8. CSS 第一步
    1. CSS first steps overview
    2. What is CSS?
    3. Getting started with CSS
    4. How CSS is structured
    5. How CSS works
    6. Using your new knowledge
  9. CSS 构建块
    1. CSS building blocks overview
    2. Cascade and inheritance
    3. CSS 选择器
    4. The box model
    5. Backgrounds and borders
    6. Handling different text directions
    7. Overflowing content
    8. Values and units
    9. Sizing items in CSS
    10. Images, media, and form elements
    11. Styling tables
    12. Debugging CSS
    13. Organizing your CSS
  10. 样式化文本
    1. Styling text overview
    2. Fundamental text and font styling
    3. Styling lists
    4. Styling links
    5. Web fonts
    6. Assessment: Typesetting a community school homepage
  11. CSS 布局
    1. CSS layout overview
    2. Introduction to CSS layout
    3. Normal Flow
    4. Flexbox
    5. Grids
    6. Floats
    7. 位置
    8. Multiple-column Layout
    9. Responsive design
    10. Beginner's guide to media queries
    11. Legacy Layout Methods
    12. Supporting Older Browsers
    13. Fundamental Layout Comprehension
  12. JavaScript — Dynamic client-side scripting
  13. JavaScript 第一步
    1. JavaScript first steps overview
    2. What is JavaScript?
    3. A first splash into JavaScript
    4. What went wrong? Troubleshooting JavaScript
    5. Storing the information you need — Variables
    6. Basic math in JavaScript — Numbers and operators
    7. Handling text — Strings in JavaScript
    8. Useful string methods
    9. 数组
    10. Assessment: Silly story generator
  14. JavaScript 构建块
    1. JavaScript building blocks overview
    2. Making decisions in your code — Conditionals
    3. Looping code
    4. Functions — Reusable blocks of code
    5. Build your own function
    6. Function return values
    7. 事件介绍
    8. Assessment: Image gallery
  15. 引入 JavaScript 对象
    1. Introducing JavaScript objects overview
    2. Object basics
    3. 对象原型
    4. Object-oriented programming concepts
    5. Classes in JavaScript
    6. Working with JSON data
    7. Object building practice
    8. Assessment: Adding features to our bouncing balls demo
  16. 异步 JavaScript
    1. Asynchronous JavaScript overview
    2. General asynchronous programming concepts
    3. Introducing asynchronous JavaScript
    4. Cooperative asynchronous Java​Script: Timeouts and intervals
    5. Graceful asynchronous programming with Promises
    6. Making asynchronous programming easier with async and await
    7. Choosing the right approach
  17. 客户端侧 Web API
    1. 客户端侧 Web API
    2. Introduction to web APIs
    3. Manipulating documents
    4. Fetching data from the server
    5. Third party APIs
    6. Drawing graphics
    7. Video and audio APIs
    8. Client-side storage
  18. Web forms — Working with user data
  19. Core forms learning pathway
    1. Web forms overview
    2. Your first form
    3. How to structure a web form
    4. Basic native form controls
    5. The HTML5 input types
    6. Other form controls
    7. Styling web forms
    8. Advanced form styling
    9. UI pseudo-classes
    10. Client-side form validation
    11. Sending form data
  20. Advanced forms articles
    1. How to build custom form controls
    2. Sending forms through JavaScript
    3. CSS property compatibility table for form controls
  21. Accessibility — Make the web usable by everyone
  22. Accessibility guides
    1. Accessibility overview
    2. What is accessibility?
    3. HTML: A good basis for accessibility
    4. CSS and JavaScript accessibility best practices
    5. WAI-ARIA basics
    6. Accessible multimedia
    7. Mobile accessibility
  23. Accessibility assessment
    1. Assessment: Accessibility troubleshooting
  24. Tools and testing
  25. Client-side web development tools
    1. Client-side web development tools index
    2. Client-side tooling overview
    3. Command line crash course
    4. Package management basics
    5. Introducing a complete toolchain
    6. Deploying our app
  26. Introduction to client-side frameworks
    1. Client-side frameworks overview
    2. Framework main features
  27. React
    1. Getting started with React
    2. Beginning our React todo list
    3. Componentizing our React app
    4. React interactivity: Events and state
    5. React interactivity: Editing, filtering, conditional rendering
    6. Accessibility in React
    7. React resources
  28. Ember
    1. Getting started with Ember
    2. Ember app structure and componentization
    3. Ember interactivity: Events, classes and state
    4. Ember Interactivity: Footer functionality, conditional rendering
    5. Routing in Ember
    6. Ember resources and troubleshooting
  29. Vue
    1. Getting started with Vue
    2. Creating our first Vue component
    3. Rendering a list of Vue components
    4. Adding a new todo form: Vue events, methods, and models
    5. Styling Vue components with CSS
    6. Using Vue computed properties
    7. Vue conditional rendering: editing existing todos
    8. Focus management with Vue refs
    9. Vue resources
  30. Svelte
    1. Getting started with Svelte
    2. Starting our Svelte Todo list app
    3. Dynamic behavior in Svelte: working with variables and props
    4. Componentizing our Svelte app
    5. Advanced Svelte: Reactivity, lifecycle, accessibility
    6. Working with Svelte stores
    7. TypeScript support in Svelte
    8. Deployment and next steps
  31. Angular
    1. Getting started with Angular
    2. Beginning our Angular todo list app
    3. Styling our Angular app
    4. Creating an item component
    5. Filtering our to-do items
    6. Building Angular applications and further resources
  32. Git and GitHub
    1. Git and GitHub overview
    2. Hello World
    3. Git Handbook
    4. Forking Projects
    5. About pull requests
    6. Mastering Issues
  33. Cross browser testing
    1. Cross browser testing overview
    2. Introduction to cross browser testing
    3. Strategies for carrying out testing
    4. Handling common HTML and CSS problems
    5. Handling common JavaScript problems
    6. Handling common accessibility problems
    7. Implementing feature detection
    8. Introduction to automated testing
    9. Setting up your own test automation environment
  34. Server-side website programming
  35. 第一步
    1. First steps overview
    2. Introduction to the server-side
    3. Client-Server overview
    4. Server-side web frameworks
    5. Website security
  36. Django Web 框架 (Python)
    1. Django web framework (Python) overview
    2. 介绍
    3. 设置开发环境
    4. Tutorial: The Local Library website
    5. Tutorial Part 2: Creating a skeleton website
    6. Tutorial Part 3: Using models
    7. Tutorial Part 4: Django admin site
    8. Tutorial Part 5: Creating our home page
    9. Tutorial Part 6: Generic list and detail views
    10. Tutorial Part 7: Sessions framework
    11. Tutorial Part 8: User authentication and permissions
    12. Tutorial Part 9: Working with forms
    13. Tutorial Part 10: Testing a Django web application
    14. Tutorial Part 11: Deploying Django to production
    15. Web application security
    16. Assessment: DIY mini blog
  37. Express Web Framework (node.js/JavaScript)
    1. Express Web Framework (Node.js/JavaScript) overview
    2. Express/Node introduction
    3. Setting up a Node (Express) development environment
    4. Express tutorial: The Local Library website
    5. Express Tutorial Part 2: Creating a skeleton website
    6. Express Tutorial Part 3: Using a database (with Mongoose)
    7. Express Tutorial Part 4: Routes and controllers
    8. Express Tutorial Part 5: Displaying library data
    9. Express Tutorial Part 6: Working with forms
    10. Express Tutorial Part 7: Deploying to production
  38. Further resources
  39. Common questions
    1. HTML questions
    2. CSS questions
    3. JavaScript questions
    4. Web mechanics
    5. Tools and setup
    6. Design and accessibility
  • Web 技术
  • Learn Web Development
  • About MDN
  • Feedback
  • 关于
  • MDN Web Docs Store
  • 联络我们
  • Firefox

MDN

  • MDN on Twitter
  • MDN on Github

Mozilla

  • Mozilla on Twitter
  • Mozilla on Instagram

© 2005- 2022 Mozilla and individual contributors. Content is available under these licenses .

  • Terms
  • Privacy
  • Cookie