26

学习Vue3.0,先从搭建环境开始

 3 years ago
source link: https://segmentfault.com/a/1190000023737670
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Bug源测试,上线来几个。愿君多修改,今夜眼难合。

这是小编关于 Vue3.0 系列文章的第二篇,本文将带您从零搭建一个基于 Vue3.0viteVue3.0 开发环境,通过本文的学习,你将学习到以下内容:

  1. 使用 vite 初始化 Vue3.0 项目
  2. 配置 ts
  3. 配置 vue-router
  4. 配置 vuex
  5. 使用 Vue3.0 开发一个 TodoList 示例

同时本文的内容已录制为视频发布到了 B站 ,可以点击链接跳转到视频地址,同时您也可以通过微信搜索【前端有的玩】关注我的公众号加我微信好友,手摸手和你一起学习 Vue3.0

使用 vite 初始化项目

vite 介绍

vite 是尤大大在今年新鼓捣出来的一个工具,尤大大对 vite 的描述是这样的: 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. 翻译成中文就是: Vite 是一个由原生 ES Module 驱动的 Web 开发构建工具。在开发环境下基于浏览器原生 ES imports 开发,在生产环境下基于 Rollup 打包。

上面这段话提到了一个关键字 ES Module ,这个是什么呢?详细的介绍大家可以访问 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Modules 进行查看。此处我们长话短说。在最早的时候,还没有前端工程化,然后我们写 javascript 都是写到一个文件,然后通过 script 标签去引用,后来随着前端发展越来越壮大, js 之间依赖越来越复杂,这时候就需要有一种可以将 JavaScript 程序拆分为可按需导入的单独模块 的机制来维护这个依赖,随之就诞生了 AMD , CMD 等等,而 ES Module 就是浏览器支持的原生模块依赖的功能。

为什么要用vite

为什么尤大大要推出 vite ,在我们使用 webpack 的时候,每次开发时候启动项目都需要几十秒甚至超过一分钟,比较慢,而且热更新也比较慢,而 vite 的主要特点就是快,官网对于 vite 的特点是这样描述的

  1. 快速的冷启动
  2. 即时的模块热更新
  3. 真正的按需编译

到底有多快呢,我们先新建一个项目试试

初始化vite项目

  1. 初始化项目, 在工作空间打开终端窗口,对于 window 用户即 cmd

    ,然后执行下面命令

    yarn create vite-app my-vue3

    执行之后就会输出以下内容,可以看到新建项目特别快,仅仅用了 1.63s

    73Qv6zb.jpg!mobile

  2. 初始化完项目,通过 cd my-vue3 进行到项目里面,然后再执行 yarn 安装依赖(此处建议使用淘宝镜像,比较快)
  3. 依赖安装完需要通过 yarn dev 启动项目

    IZZBFrv.jpg!mobile

    是不是瞬间体验到了秒启项目的感觉,启动之后就可以通过 http://localhost:3000 来访问项目了

查看项目结构

使用 vscode 打开项目之后,可以查看到新建的项目结构与 vue-cli4 创建的项目结构基本一样,都是我们很熟悉的 App.vuemain.js

aI7Fjyf.jpg!mobile

查看main.js文件内容

打开 main.js

import { createApp } from 'vue'

import App from './App.vue'

import './index.css'

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

发现创建 Vue 的方式变了,原来是通过 new Vue 的方法来初始化 Vue ,在 Vue3.0 中,修改为了通过 createApp 的方式,关于 Vue3.0 的更多使用方式,我们将在后面的系列文章中逐渐为您带来讲解。

配置typescript

typescript 现在已经成为了前端必备技能之一,大量的项目也开始基于 typescript 进行开发。在使用 Vue2.0 的时候,因为 Vue2.0 没有对 typescript 进行支持,所以使用 ts 开发功能显示有些别扭。但到了 Vue3 ,其自身源码便是基于 ts 开发的,所以对 ts 天生有着很好的支持。使用 vite 配置 typescript 很简单,只需要进行以下几步操作.

  1. 安装 typescript

    yarn add typescript -D

  2. 初始化 tsconfig.json

    # 然后在控制台执行下面命令

    npx tsc --init

  3. main.js 修改为 main.ts ,同时将 index.html 里面的引用也修改为 main.ts , 通过还需要修改 App.vueHelloWorld.vue 文件,修改方式如下

    <!--将 <script> 修改为 <script lang="ts">-->

    <script lang="ts">

    import HelloWorld from './components/HelloWorld.vue'

    export default {

    name: 'App',

    components: {

    HelloWorld

    }

    }

    </script>

    修改完之后,重启就可以访问项目了。虽然这样配置是可以了,但是打开 main.ts 会发现 import App from App.vue 会报错: Cannot find module './App.vue' or its corresponding type declarations. ,这是因为现在 ts 还没有识别 vue 文件,需要进行下面的配置:

    1. 在项目根目录添加 shim.d.ts 文件
    2. 添加以下内容

      declare module "*.vue" {

      import { Component } from "vue";

      const component: Component;

      export default component;

      }

接下来你就可以开开心心的在组件中使用`ts`了

配置 vue-router

Vue2.0 中我们路由一般会选择使用 vue-router ,在 Vue3.0 依然可以使用 vue-router ,不过和 Vue3.0 一样当前 vue-router 的版本也是 beta 版本,在本文撰写的时候,版本是 4.0.0-beta7

安装 vue-router

因为当前 vue-router 针对 vue3.0 的版本还是 beta 版本,所以不能直接通过 yarn add vue-router 进行安装,而是需要带上版本号

yarn add [email protected]

配置vue-router

在项目 src 目录下面新建 router 目录,然后添加 index.ts 文件,在文件中添加以下内容

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

// 在 Vue-router新版本中,需要使用createRouter来创建路由

export default createRouter({

// 指定路由的模式,此处使用的是hash模式

history: createWebHashHistory(),

// 路由地址

routes: []

})

与新的 Vue3.0 初始化方式发生变化一样, vue-router 的初始化方式也发生了变化,变成了通过 createRouter 来初始化路由。

router 引入到 main.ts

修改 main.ts 文件内容如下

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')

配置 vuex

vue-router 一样,新的 vuex 当前也处于 beta 版本,当前版本是 4.0.0-beta.4

安装vuex

yarn add [email protected]

配置vuex

在项目 src 目录下面新建 store 目录,并添加 index.ts 文件,文件中添加以下内容

import { createStore } from 'vuex'

interface State {

userName: string

}

export default createStore({

state(): State {

return {
  userName: "子君",
};

},

});

引入到 main.ts

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')

开发TodoList

通过上面的一系列操作,我们的开发环境就已经配置完成了,接下来我们就通过新的开发环境先开发一个 TodoList ,来验证一下是否正常。

添加 todolist 页面

  1. 首先我们先在 src 目录下面新建一个 views 目录,然后在其中新建文件 todo-list.vue ,并为文件添加以下内容

    <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>

    调整路由

    1. 首先将 App.vue

      文件内容修改为

      <template>

      <router-view></router-view>

      </template>

      <script lang="ts">

      export default {

      name: 'App'

      }

      </script>

    2. 然后修改 router/index.ts 文件,添加新的路由

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

      // 在 Vue-router新版本中,需要使用createRouter来创建路由

      export default createRouter({

      // 指定路由的模式,此处使用的是hash模式

      history: createWebHashHistory(),

      // 路由地址

      routes: [{

      path: '/todolist',
      // 必须添加.vue后缀
      component: () => import('../views/todo-list.vue')

      }]

      })

      这时候我们就可以通过 http://localhost:3000/#/todolist 来访问 TodoList 了,效果如下图所示

      UvuErqF.jpg!mobile

总结

到此,我们 Vue3.0 的开发环境算是搭建完成了,当然现在还有好多好多要完善的东西,比如我们还需要去调整一下 typescript 的配置,然后添加 eslint 等等。同时如何在组件中跳转路由,使用 vuex 还没有去讲解,不过至少我们已经起步了,更多的内容将会在下一篇文章中讲到。本文首发于公众号【前端有的玩】,欢迎关注加我好友,我们一起探讨 Vue3.0


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK