Start learning Vue3.0, first set up the environment

This article is reproduced from the WeChat public account: Some of the front-end play, the author's front-end attacker

This article will take you from zero to build a basis Vue3.0of vitethe Vue3.0development environment, by learning this article, you will learn the following:

  1. Use the viteinitial Vue3.0project

  2. Configurationts

  3. Configurationvue-router

  4. Configurationvuex

  5. Use to Vue3.0develop an TodoListexample

One, use the viteinitialization project

vite introduction

viteIt is a new tool created by Youda this year, and vitethe description of it is this: Vite is an opinionated web dev build tool that serves your code via native ES Module imports during dev and bundles it with Rollup for production. Translated into Chinese means: Vite is a  development and construction tool ES Module driven  by native  Web. It is based on the browser's native  ES imports development in the development environment, and based on the Rolluppackaging in the production environment .

Why use vite

Why is it especially launched? viteWhen we use webpackit, it takes tens of seconds or even more than a minute to start a project every time it develops, which is relatively slow, and hot updates are relatively slow, and vitethe main feature is fast. The official website viteis characterized by Described like this

  1. Fast cold start

  2. Instant module hot update

  3. True on-demand compilation

How fast is it? Let’s try a new project first

Initialize the vite project

  1. Initialize the project, open a terminal window in the workspace, for the windowuser, cmdand then execute the following command

    yarn create vite-app my-vue3
    

    After the execution, the following content will be output, you can see that the new project is very fast, just use1.63s

  2. After initializing the project, cd my-vue3go to the project and then execute the yarninstallation dependency (it is recommended to use Taobao mirror here, which is faster)

  3. Dependent installation needs to yarn devstart the project

    Did you experience the feeling of the Miaoqi project in an instant? After starting, you can http://localhost:3000access the project

View project structure

After using the vscodeopen project, you can see that the newly vue-cli4created project structure is basically the same as the created project structure, which are both familiar App.vueandmain.js

View the contents of the main.js file

turn onmain.js

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


createApp(App).mount('#app')


Found that Vuethe method of creation has changed. The original new Vuemethod is used to initialize Vue. In Vue3.0, the method of modification is changed to pass createApp. For Vue3.0more usage methods, we will gradually explain to you in the following series of articles.

Two, configure typescript

typescriptIt has now become one of the necessary front-end skills, and a large number of projects have begun to typescriptbe developed based on them. When using Vue2.0it, because Vue2.0there is no typescriptsupport for it, it is a tsbit awkward to use the development function. But when it comes Vue3, its own source code is based on tsdevelopment, so it tshas good support for innate. The viteconfiguration typescriptis very simple, only the following steps are required.

  1. installation typescript

    yarn add typescript -D
    
  2. initializationtsconfig.json

    # 然后在控制台执行下面命令
    npx tsc --init
    
  3. Will be main.jsmodified to main.ts, and index.htmlthe reference inside will also be modified to main.ts, through the need to modify App.vueand HelloWorld.vuefile, the modification method is as follows

    <!--将 <script> 修改为 <script lang="ts">-->
    <script lang="ts">
    import HelloWorld from './components/HelloWorld.vue'
    
    export default {
      name: 'App',
      components: {
        HelloWorld
      }
    }
    </script>
    
    

    After the modification, restart to access the project. Although this configuration is possible, you main.tswill find an import App from App.vueerror when you open it :,  Cannot find module './App.vue' or its corresponding type declarations.This is because the file tshas not been recognized yet vue, and the following configuration is required:

    Then you can happily use tsit in the component

    1. Add shim.d.tsfiles to the project root directory

    2. Add the following

      declare module"*.vue" {
        import { Component } from"vue";
        const component: Component;
        exportdefault component;
      }
      

Three, configuration vue-router

In Vue2.0the route we will generally choose to use vue-router, in Vue3.0use remain vue-router, however, and Vue3.0as the current vue-routerversion is the betaversion at the time of this writing, the version is4.0.0-beta7

installationvue-router

Because the current vue-routerfor the vue3.0version or betaversions can not be directly yarn add vue-routerinstalled, but need to bring the version number

yarn add [email protected]

Configure vue-router

srcCreate a new routerdirectory under the project directory , then add a index.tsfile, add the following content to the file

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


// 在 Vue-router新版本中,需要使用createRouter来创建路由
exportdefault createRouter({
  // 指定路由的模式,此处使用的是hash模式
  history: createWebHashHistory(),
  // 路由地址
  routes: []
})

Vue3.0Just as the new initialization method has changed, vue-routerthe initialization method has also changed, becoming a pass createRouterto initialize routing.

It will be routerintroduced into main.tsthe

Modify the main.tscontents of the file as follows

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


const  app = createApp(App)
// 通过use 将 路由插件安装到 app 中
app.use(router)
app.mount('#app')


Four, configure vuex

Same vue-routeras the new vuexcurrent betaversion, the current version is4.0.0-beta.4

Install vuex

yarn add [email protected]

Configure vuex

srcCreate a new storedirectory under the project directory , and add a index.tsfile, add the following content to the file

import { createStore } from'vuex'


interface State {
  userName: string
}


exportdefault createStore({
  state(): State {
    return {
      userName: "子君",
    };
  },
});

Introduced into main.tsthe

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


const  app = createApp(App)
app.use(router)
app.use(store)
app.mount('#app')

Develop TodoList

Through the above series of operations, our development environment has been configured, and then we will first develop one through the new development environment TodoListto verify whether it is normal.

Add todolistpage

  1. First, we first srccreate a new directory under the viewsdirectory, then create a new file in it todo-list.vue, and add the following content to the file

    <template>
      <div class="todo-list">
        <div>
          <label>新增待办</label>
           <input v-model="state.todo" @keyup.enter="handleAddTodo">
        </div>
        <div>
          <h3>待办列表({
         
         {todos.length}})</h3>
          <ul>
            <li v-for="item in todos" :key="item.id" @click="handleChangeStatus(item, true)">
              <input type="checkbox">
              <label>{
         
         {item.text}}</label>
            </li>
          </ul>
        </div>
        <div><h3>已办列表({
         
         {dones.length}})</h3></div>
        <ul>
          <li v-for="item in dones" :key="item.id" @click="handleChangeStatus(item, false)">
              <input type="checkbox" checked>
              <label>{
         
         {item.text}}</label>
            </li>
        </ul>
      </div>
    </template>
    <script lang="ts">
     // 在vue2中 data 在vue3中使用 reactive代替
    import { reactive, computed } from 'vue'
    import { useRouter } from 'vue-router'
    export default {
      // setup相当于vue2.0的 beforeCreate和 created,是vue3新增的一个属性,所有的操作都在此属性中完成
      setup(props, context) {
        // 通过reactive 可以初始化一个可响应的数据,与Vue2.0中的Vue.observer很相似
        const state = reactive({
          todoList: [{
            id: 1,
            done: false,
            text: '吃饭'
          },{
            id: 2,
            done: false,
            text: '睡觉'
          },{
            id: 3,
            done: false,
            text: '打豆豆'
          }],
          todo: ''
        })
        // 使用计算属性生成待办列表
        const todos = computed(() => {
          return state.todoList.filter(item => !item.done)
        })
    
        // 使用计算属性生成已办列表
        const dones = computed(() => {
          return state.todoList.filter(item => item.done)
        })
    
        // 修改待办状态
        const handleChangeStatus = (item ,status) => {
          item.done = status
        }
        
        // 新增待办
        const handleAddTodo = () => {
          if(!state.todo) {
            alert('请输入待办事项')
            return
          }
          state.todoList.push({
            text: state.todo,
            id: Date.now(),
            done: false
          })
          state.todo = ''
        }
    
    // 在Vue3.0中,所有的数据和方法都通过在setup 中 return 出去,然后在template中使用
        return {
          state,
          todos,
          dones,
          handleChangeStatus,
          handleAddTodo
        }
      }
    }
    </script>
    <style scoped>
    .todo-list{
      text-align: center;
    }
    
    .todo-list ul li {
      list-style: none;
    }
    </style>
    

    Adjust routing

    1. First App.vuemodify the content of the file to

      <template>
        <router-view></router-view>
      </template>
      
      <script lang="ts">
      
      export default {
        name: 'App'
      }
      </script>
      
    2. Then modify the  router/index.tsfile and add a new route

      import {createRouter, createWebHashHistory} from'vue-router'
      
      // 在 Vue-router新版本中,需要使用createRouter来创建路由
      exportdefault createRouter({
        // 指定路由的模式,此处使用的是hash模式
        history: createWebHashHistory(),
        // 路由地址
        routes: [{
          path: '/todolist',
          // 必须添加.vue后缀
          component: () =>import('../views/todo-list.vue')
        }]
      })
      

      At this time, we can http://localhost:3000/#/todolistvisit TodoListthrough, the effect is shown in the figure below

to sum up

At this point, our Vue3.0development environment is considered complete. Of course, there are still many things to be improved. For example, we need to adjust typescriptthe configuration and add it eslint

Guess you like

Origin blog.csdn.net/AN0692/article/details/108736770