Nuggets team number online, help you Offer impromptu! Click for details

@ Vue3 + Vite + TypeScript ToDoList

Do not brush, only punch; Go to Denver and get the offer!

preface

I hear and I fogorget.

I see and I remember.

I do and I understand.

The small white lesson series is completed, now we start the actual combat course!

  • Note: This project is based on Vue3 + Vite + TypeScript framework

The body of the

If you finish watching “Vue Little White Lesson”, then you have a certain understanding of the overall situation of Vue3 project, and build a Vue3 environment. In this article, we will practice Vue3 to implement the ToDoList project.

If you are not familiar with the VueCLI project, please refer to:

  • Vue Little White Lesson (5) — Vue3 + Vite and VueCLI4 project construction

Here is our built project directory structure:

Introduction to main documents

In this ToDoList, the knowledge points involved include the following:

Entry file —main.js

In 2.X, creating an instance of vue is done by using new vue (), and in 3.X it is done by using the createApp API.

// Enter the createApp module first
import { createApp } from 'vue'
import App from './App.vue'

// Use the createApp method to put our entry file in and finally mount it
createApp(App).mount('#app')
Copy the code

The root component –App.vue

App.vue is the root component of our project. All the components are mounted to it.

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld msg="Hello Vue 3 + TypeScript + Vite" />
</template>

<script lang="ts">
// Introduce defineComponent() to correctly infer the parameter types of the Setup () component
import { defineComponent } from 'vue'
import HelloWorld from './components/HelloWorld.vue'

export default defineComponent({
  name: 'App'.components: {
    HelloWorld,
  },
})
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
Copy the code

We see defineComponent, which simply wraps the setup function and returns the options object.

export function defineComponent(options: unknown) {
  return isFunction(options) ? { setup: options } : options
}
Copy the code

The most important thing about defineComponent is that it gives components proper argument type inference in TypeScript.

Business component —HelloWorld.vue

Helloworld.vue is the component we will write the business to. Delete some initialization display, our component looks like this:

<template>
  <h1>{{ msg }}</h1>
</template>

<script lang="ts">
import { ref, defineComponent } from 'vue'
export default defineComponent({
  name: 'HelloWorld'.props: {
    msg: {
      type: String.required: true,}},The setup function is an entry point to the Composition API
  // Almost everything is in the setup() method, including the mounted lifecycle hooks.
  setup: () = > {
    const count = ref(0)
    return { count }
  },
})
</script>

<style scoped></style>
Copy the code

If you are familiar with the Vue 2 project, the setup function should be the most obvious one when you see this component. This is one of the features of Vue 3, the composite API

Let’s compare the Options API (Vue 2) with the Composition API (Vue 3).

Options API conventions:

  • We need to set the receive parameters in props

  • We need to set variables inside data

  • We need to set computing properties in computed

  • We need to set the listening properties in watch

  • We need to set event methods inside methods

You’ll notice that the Options APi dictates where we should do what, which in turn forces us to split code to some extent.

This fragmentation makes it difficult to understand and maintain complex components. The separation of options masks a potential logical problem. In addition, when dealing with a single logical concern, we must constantly “jump” to the option blocks of the related code.

Now with the Composition API, this is no longer the convention, so the organization of code is very flexible, and our control code can be written inside the Setup.

The setup function features:

  1. The setup function is a function between the lifecycle beforeCreate and Created hook functions, so data and methods cannot be used in the setup function

  2. The setup function is the entry point to the Composition API

  3. Variables and methods defined in the setup function must eventually be returned or not used in the template

Some notes about the setup function:

  1. Since the Created lifecycle methods are not executed at the time the Setup function is executed, the variables and methods of data and methods cannot be used in the setup function

  2. Since we can’t use data and methods in the setup function, Vue changes this to undefined in order to avoid our error

  3. Setup functions can only be synchronous, not asynchronous

Start implementing ToDoList

With the main documentation for the Vue 3 project covered, we are ready to implement the ToDoList project.

Create the ToDoList component

We can rename the helloworld. vue file in/SRC /components to todolist. vue and change the name to ToDoList as well, removing unnecessary content from its

<template>
  <h1>{{ msg }}</h1>
</template>
Copy the code

2. Introduce the ToDoList component

In the app. vue file of/SRC, change the original registration of HelloWorld to ToDoList, and change the value MSG content to ToDoList, as follows:

<template>
  <ToDoList msg="ToDoList" />
</template>

<script lang="ts">
// Introduce defineComponent() to correctly infer the parameter types of the Setup () component
import { defineComponent } from 'vue'
import ToDoList from './components/ToDoList.vue'

export default defineComponent({
  name: 'App'.components: {
    ToDoList,
  },
})
</script>
Copy the code

OK, with the above two steps done, our project runs like this:

Meet Props

Props is used by the parent component to pass data to the child component

The scope of a component instance is isolated. This means that you cannot (and should not) directly reference the parent component’s data in the child component’s template. To make a child component use the parent component’s data, you need to pass the props option of the child component. It comes in two forms: dynamic and static

  • Static props
<blog-post title="My journey with Vue"></blog-post>
Copy the code
  • Dynamic props

In a template, to dynamically bind the parent component’s data to the props of the child component template, use the V-bind as with the Html tag feature;

<! Dynamically assign a value to a variable -->
<blog-post v-bind:title="post.title"></blog-post>
Copy the code

Create and render the list

Next, we create an array of items in the setup function, remember to return the array, then write our HTML structure in

<template>
  <h1>{{ msg }}</h1>
  <ul class="ToDoList">
    <li v-for="(item, index) in items" :key="item.id">
      <! -- To-do list -->
      <span v-text="item.title"></span>
      <! -- Finish button -->
      <button>complete</button>
    </li>
  </ul>
</template>

<script lang="ts">
import { ref, defineComponent } from 'vue'
export default defineComponent({
  name: 'ToDoList'.props: {
    msg: {
      type: String.required: true,}},The setup function is an entry point to the Composition API
  // Almost everything is in the setup() method, including the mounted lifecycle hooks.
  setup: () = > {
    const items = ref([
      {
        id: 1.title: 'eat'}, {id: 2.title: 'sleep'}, {id: 3.title: 'Beat the beans',}])// Note: the value must be returned, otherwise it will not be retrieved in the template.
    return { items }
  },
})
</script>

<style scoped></style>
Copy the code

In setup, we return an array of items, where each element contains id and title. We bind items to the list using v-for.

Note:

  1. The list loop in VUE needs to add :key=” unique identifier “. The unique identifier can be the ID and index in item, etc. Because vUE components are highly reusable, adding key can identify the uniqueness of components. To better differentiate between components, the key’s main purpose is to update the virtual DOM efficiently. For more details, please refer to VUE

  2. In the setup function, you can use the ref function to create a reactive data and ruturn it out; Vue automatically updates the UI when the data changes,

4. Bind the delete event

Next we use V-on to bind events to the button to remove the corresponding option from the list when the delete button is clicked.

<button v-on:click="deleteItem(index)">complete</button>
Copy the code

Here we have added a click method called deleteItem that takes an array subscript index (numeric type).

Following the deleteItem method defined above, we then define the deleteItem event in setup and return it

// Click the Finish button to delete the corresponding item
let deleteItem = (index: number) = > {
  items.value.splice(index, 1)}Copy the code

Note:

There is no this in the setup function, and all ref objects need a value attribute to get their value in JS

5. Use the input field to add new items

So far we have used ready-made lists. Now we use the input field to dynamically add entries to the list:

<div>To do:<input type="text" v-model="newItem" />
  <button @click="addNewItem">add</button>
</div>
Copy the code

Use the v-Model directive to create a bidirectional binding on a form control or component, that is, bind newItem, bind event listeners with @, and click the Add button to respond to the event addNewItem.

AddNewItem is also written in setup as follows:

// Click the Add button to add a new to-do list
let addNewItem = () = > {
  // The input box is not null
  if(! newItem.value) {return
  }
  // Use push to add new elements to the array
  let obj = {
    id: id, // id is unique and incremented
    title: newItem.value, / / todo title
  }
  items.value.push(obj)
  / / id since
  id++
  // Empty the input field
  newItem.value = ' '
}
Copy the code

In setup, we declare a variable whose ID defaults to 0, items defaults to an empty array, and newItem is an empty string. After entering the content in the input box, click “Push” in “Items” of “Add” button, including ID and title. Then the ID is increased automatically and the input box is cleared at last.

conclusion

Through the above key knowledge points, we finally realized the basic functions of ToDoList, and the results are as follows:

Add more styles if you like.

The road ahead is long, and I see no end.

References:

  • Vue website
  • Vue3.0 setup using | CSDN small 99 – front end
  • What does Vue3 – defineComponent solve? | CSDN – Austin
  • Using Vue3 + TS to develop a application | CSDN – Maddix TODOList

The attached ToDoList. Vue code

<template> <h1>{{MSG}}</h1> <input type="text" v-model="newItem" /> <button @click="addNewItem"> </button> < div> <ul class="ToDoList"> <li v-for="(item, index) in items" :key="item.id"> <! <span v-text="item.title"></span> <! <button V-on :click="deleteItem(index)"> </button> </li> </ul> </template> <script lang="ts"> import {ref, defineComponent } from 'vue' export default defineComponent({ name: 'ToDoList', props: { msg: { type: String, required: The setup function is the entry point to the Composition API // Almost everything is in the setup() method, including the mounted lifecycle hooks. Setup: () = > {const items = ref ([{id: 1, the title: 'eating'}, {id: 2, the title: 'sleep'}, {id: 3, the title: },]) let newItem = ref('') // id id = 0 let deleteItem = (index: Number) => {items.value.splice(index, 1)} let addNewItem = () => {if (! Newitem. value) {return} let obj = {id: id, // title: Newitem. value, // todo title} items.value.push(obj) // add id++ // empty the input box newitem. value = ""} // Note: Return must be returned, otherwise the value will not be retrieved in the template. return { items, id, newItem, deleteItem, addNewItem } }, }) </script> <style scoped></style>Copy the code

Postscript: Hello friends, if you think this article is good, remember to give a thumbs-up or star, your thumbs-up and star is my motivation to write more and richer articles!Making the address



dbThe document library 由 dbusingCreative Commons Attribution – Non-commercial Use – Same way Share 4.0 International LicenseGrant permission.

Based on thegithub.com/danygitgitOn the creation of works.

Use rights other than those authorized by this License agreement may be obtained from
Creativecommons.org/licenses/by…Obtained.