After Vue 3 came out, a lot of people thought, “I have to learn something new again”, “I can’t learn any more” and so on.

But things always have its two sides, front-end knowledge update quickly, good studious students. Computer industry iteration speed is very fast, in the computer field, is the front wave is patted on the beach relatively fast.

I envy my classmates who are still at school, because today’s college students have much more access to information than I did when I was in college. I hope you can cherish this opportunity and learn new knowledge well. I hope you will not be beaten up when you enter the society.

In my opinion, the best way to learn a new technology is to use a Demo to create a usage scenario and go through the API. How far do you need to go?

Probably is what the scene with what API can be such as heart, and then in plain English a little bit is that you can write the code before using Vue2. X, with Vue 3 no difference refactoring again.

Three ways to build Vue3.0

For now, there are three ways to build a Vue 3 project.

1. Command-line interface (CLI)

For Vue 3, you should use Vue CLI v4.5 available on NPM as @vue/cli@next. To upgrade, you should need to reinstall the latest version of @vue/cli globally:

yarn global add @vue/cli@next
# OR
npm install -g @vue/cli@next
Copy the code

2, Vite

Vite is a Web development build tool that allows for quick code provisioning due to its native ES module import approach.

You can quickly set up a Vue project using Vite by running the following command in your terminal.

Use NPM:

npm init vite-app <project-name>
cd <project-name>
npm install
npm run dev
Copy the code

3, Webpack

In the early days when vue-CLI did not support the creation of Vue 3 projects, the Vue team created a Webpack project configuration on Github that could be directly cloned for use.

git clone https://github.com/vuejs/vue-next-webpack-preview.git demov3
cd demov3
npm install
npm run dev
Copy the code

It is not recommended to use this method, there are two above now ~ ~

(When we used to look at the stars and moon, we called them “Little Sweet”. Now the new couple wins the old one, and we call them “Lady cow”.)

Code practice

We choose relatively fresh Vite to build the project, to play with the most fashionable. My local Node version is V12.6.0, so try to be consistent.

Build the project

npm init vite-app todo-v3
cdTodo -v3 NPM install // You are advised to use the Taobao image CNPM install NPM run devCopy the code

After the startup, as shown below, it is successful:

The entry page

The first thing that catches your eye is the change to main.js:

/ / the Vue 3.0
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'

createApp(App).mount('#app')
Copy the code
// Vue 2.x
import Vue from 'vue'
import App from './App.vue'

new Vue({
  render: h= > h(App)
}).$mount('#app')
Copy the code

The first part of the code is to create Vue instance of Vue 3, through the form of createApp, you don’t say, and React really like 😄.

The second section is the creation of Vue 2.x in the form of a Vue instance, created in the form of new.

The vue-router route was added

As of now, Vue-Router-Next has been updated to v4.0.0-beta.12.

If you use CNPM install vue-router to install route, it will download to vue-router 3.x version, we need to use:

cnpm install vue-router@next -S
Copy the code

After the installation is complete, we start to configure the route of the project. In the SRC directory, create the rourer folder. In the folder, create the index.js file and add the following contents:

import {createRouter, createWebHashHistory} from 'vue-router'

export default createRouter({
  history: createWebHashHistory(),
  routes: []})Copy the code

The routing mode of Vue 2.x is controlled by setting the mode option to History or hash.

In Vue 3, the route instance is created by createRouter. The history attribute is used as a parameter to control the routing mode. The createWebHashHistory method returns the hash mode. CreateWebHistory returns history mode. This project uses hash mode.

Again, we need to introduce the Router instance in mian. Js:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import './index.css'

createApp(App).use(router).mount('#app')
Copy the code

Example Add the global state Vuex

Vuex has been updated to V4.0.0-beta.4, so we need to install it with the following command:

cnpm i vuex@next -S
Copy the code

Next, create the store folder in the SRC directory, create the index.js file, and add the following code:

// Vue 3
import { createStore } from 'vuex'

export default createStore({
  state() {
    return {
      author: "Thirteen"}; }});Copy the code

Vue 2.x

// Vue 2.x
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state,
  mutations,
  actions,
  modules: {}})Copy the code

Also using the new writing, create an instance of vuex using the createStore method thrown inside vuex.

Next we introduce it into main.js:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './index.css'

// String calls
createApp(App).use(router).use(store).mount('#app')
Copy the code

Introduction of Antd for Vue3 version component library

Antdv2.x is a new generation of Vue 3.0 component library developed by Tang Jinzhou teacher (Hangzhou Xiaobao online). Let’s have a try. Here we download it by the following command:

cnpm i --save ant-design-vue@next -S
Copy the code

Introduce the ant-design-vue component in mian. Js as follows:

import { createApp } from 'vue'
import Antd from 'ant-design-vue';
import App from './App.vue'
import router from './router'
import store from './store'
import 'ant-design-vue/dist/antd.css';
import './index.css'

// This tutorial uses the global import component library

createApp(App).use(router).use(store).use(Antd).mount('#app')
Copy the code

To test the success, explain how Vue 3 declares variables and how to change them with methods:

<template>
  <a-button @click="add" type="primary">I'm going to add {{count}}</a-button>
  <a-button @click="add2('a')" type="primary">A {{state. A}}</a-button>
  <a-button @click="add2('b')" type="primary">{{state.b}}</a-button>
</template>

<script>
import { ref, reactive } from 'vue'
export default {
  setup() {
    const count = ref(0)
    const state = reactive({
      a: 0.b: 0,})const add = () = > {
      count.value += 1
    }
    const add2 = (type) = > {
      state[type] += 1
    }
    return {
      state,
      count,
      add,
      add2
    }
  }
}
</script>
Copy the code

As shown in the above code, the new setup method in Vue 3 overturns the traditional options property. We can write all the business logic in the setup method.

We have two ways to declare variables:

  • Ref: This is used to declare simple base type variables such as single numbers, Boolean, strings, and so on.
  • Reactive: This is used for complex variables of object reference types.

All declared variables and methods that are intended to be used in the template must return in the setup method, otherwise they cannot be called. Return {{count}} and {{state. A}}. The effect is as follows:

TODO

First, create a new views folder to place the page components. Create a todo.vue file inside the views, as shown below:

<template>
  <div id="components-layout-demo-basic">
    <a-layout>
      <a-layout-header>todo</a-layout-header>
      <a-layout-content>content</a-layout-content>
    </a-layout>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
export default {
  setup(){}}</script>

<style scoped>
  #components-layout-demo-basic {
    min-height: 100vh;
    max-width: 40%;
    margin: 0 auto;
    background-color: #ededed;
  }
  #components-layout-demo-basic .ant-layout-header.#components-layout-demo-basic .ant-layout-footer {
    background: #7dbcea;
    text-align: center;
    color: #fff;
  }
</style>
Copy the code

Introduce the antD-V layout component and give some basic styles.

Then go to app.vue and router/index.js and make the following changes:

// App.vue
<template>
  <router-view></router-view>
</template>

<script>
export default {
  name: 'App'
}
</script>
Copy the code
import {createRouter, createWebHashHistory} from 'vue-router'

export default createRouter({
  history: createWebHashHistory(),
  routes: [{path: '/todo'.component: () = > import('.. /views/todo.vue')}]})Copy the code

If the following information is displayed, the configuration is successful:

Add new to-do items input box:

<template>
  <div id="components-layout-demo-basic">
    <a-layout>
      <a-layout-header>todo</a-layout-header>
      <a-layout-content>
        <a-input-search
          v-model:value="todo"
          placeholder="Please enter what you want to do"
          size="large"
          @search="addTodo"
        >
          <template v-slot:enterButton>
            <a-button>new</a-button>
          </template>
        </a-input-search>
      </a-layout-content>
    </a-layout>
  </div>
</template>
<script>
import { ref, reactive } from 'vue'
import { ref, reactive } from 'vue'
export default {
  setup() {
    const todo = ref(' ')

    const addTodo = (value) = > {
      console.log(value)
    }
    return {
      todo,
      onSearch
    }
  }
}
</script>
Copy the code

As shown in the figure below:

Add the “To Do” and “Done items” templates as follows:

<template>
  <div id="components-layout-demo-basic">
    <a-layout>
      <a-layout-header>todo</a-layout-header>
      <a-layout-content>
        <a-input-search
          v-model:value="todo"
          placeholder="Please enter what you want to do"
          size="large"
          @search="addTodo"
        >
          <template v-slot:enterButton>
            <a-button>new</a-button>
          </template>
        </a-input-search>
        <h2 class="title">todo</h2>
        <a-card title="Title">
          <template v-slot:extra>
            <a-switch />
          </template>In general</a-card>
        <h2 class="title">Already backlog items</h2>
        <a-card title="Title">
          <template v-slot:extra>
            <a-switch />
          </template>In general</a-card>
      </a-layout-content>
    </a-layout>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
export default {
  setup() {
    const todo = ref(' ')

    const addTodo = (value) = > {
      console.log(value)
    }
    return {
      todo,
      onSearch
    }
  }
}
</script>

<style scoped>
  #components-layout-demo-basic {
    min-height: 100vh;
    max-width: 40%;
    margin: 0 auto;
    background-color: #ededed;
  }
  #components-layout-demo-basic .ant-layout-header.#components-layout-demo-basic .ant-layout-footer {
    background: #7dbcea;
    color: #fff;
    text-align: center;
  }
  .title {
    margin: 0;
    padding: 10px;
  }
</style>
Copy the code

The effect is as follows:

Next, let’s add the logic for the agent:

<template>
  <div id="components-layout-demo-basic">
    <a-layout>
      <a-layout-header>todo</a-layout-header>
      <a-layout-content>
        <a-input-search
          v-model:value="todo"
          placeholder="Please enter what you want to do"
          size="large"
          @search="addTodo"
        >
          <template v-slot:enterButton>
            <a-button>new</a-button>
          </template>
        </a-input-search>
        <h2 class="title">todo</h2>
        <a-card :title="' ${index + 1}, ${item.time} '" v-for="(item, index) in todos" :key="item.id">
          <template v-slot:extra>
            <a-switch v-model:checked="item.done" @change="handleCheck(item, true)" />
          </template>
          {{ item.content }}
        </a-card>
        <h2 class="title">Already backlog items</h2>
        <a-card :title="' ${index + 1}, ${item.time} '" v-for="(item, index) in dones" :key="item.id">
          <template v-slot:extra>
            <a-switch v-model:checked="item.done" @change="handleCheck(item, false)" />
          </template>In general</a-card>
      </a-layout-content>
    </a-layout>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
export default {
  setup() {
    const todo = ref(' ')
    const time = `The ${new Date().getFullYear()}-The ${new Date().getMonth()}-The ${new Date().getDate()}`

    const state = reactive({
      todoList: [{id: 1.done: false.time: time,
          content: 'Go to the old eight canteen and have lunch together.'
        },
        {
          id: 2.done: false.time: time,
          content: 'A duet with Giao.'
        },
        {
          id: 3.done: false.time: time,
          content: 'Do a little bit of high demand'}]})// Add a to-do list
    const addTodo = (value) = > {
      if(! value) { message.error('Please enter a to-do')
        return
      }
      state.todoList.push({
        content: value,
        id: Date.now(),
        time: time,
        done: false
      })
      todo.value = ' '
    }
    // Calculate the resulting to-do list by calculating the attributes
    const todos = computed(() = > {
      return state.todoList.filter(item= >! item.done) })// Calculate the resulting done list by calculating the attributes
    const dones = computed(() = > {
      return state.todoList.filter(item= > item.done)
    })
    // Modify the state method
    const handleCheck = (item ,status) = > {
      item.done = status
    }

    return {
      todo,
      addTodo,
      state,
      todos,
      dones,
      handleCheck
    }
  }
}
</script>

<style scoped>
  #components-layout-demo-basic {
    min-height: 100vh;
    max-width: 40%;
    margin: 0 auto;
    background-color: #ededed;
  }
  #components-layout-demo-basic .ant-layout-header.#components-layout-demo-basic .ant-layout-footer {
    background: #7dbcea;
    color: #fff;
    text-align: center;
  }
  .title {
    margin: 0;
    padding: 10px;
  }
</style>
Copy the code

If we use computed in setup and receive a callback function, all variables in the callback function will be listened on. For example, state.todolist is already listened on. If we change the state of our to-do in handleCheck, we will also be listened on computed. The template will be refreshed with the following effect:

conclusion

Vue 3.0 still has a lot of knowledge worth exploring. The above content is simply to teach you how to start building a project and how to combine the component library with the new API. In the future, I will continue to sort out other practical techniques. Warehouse address: github.com/newbee-ltd/… , this warehouse will not regularly update a variety of Vue3.0 related knowledge and a variety of integration of Demo and Vue3 use tips, you can pay attention to, what suggestions are also welcome to give me a message.