Vue3-使用@vue/cli搭建項目

1、Vue3簡介
2020年9月,Vue.js3.0'One Piece'正式版發佈,vue3支持vue2大多數特性,並更好的支持Typescript.
性能方面,相比Vue2,vue3的性能提高了許多html

  • 打包大小減小41%
  • 初次渲染快55%,更新渲染快133%
  • 內存減小54%
  • 使用Proxy代替defineProterty實現數據響應式
  • 重寫虛擬DOM的實現和Tree-Shaking(精簡模塊,去掉未使用過的)

2、使用vue-cli建立vue3項目
一、檢查vue-cli版本,必須在4.5.0以上vue

vue -V

二、若版本太低,需升級(Vue CLI由原來的vue-cli改爲了@vue/cli。若已經全局安裝了舊版本的vue-cli須要經過npm uninstall vue-cli -g卸載)node

npm install -g @vue/cli

三、建立項目web

vue create my-project

image.png

  • 選擇第三個,按Enter

image.png

  • 而後選擇TypeScript,按空格選中。(暫時不選vue-router和vuex)
  • 按Enter

image.png

  • 選3.x
  • 以後的一直Enter

image.png
建立完成,cd到建立的項目路徑下,輸入npm run serve開啓一個node服務vue-router

四、項目簡介vuex

  • 項目結構

image.png

  • main.ts
//程序的主入口文件,(ts文件)
//引入createApp函數,建立對應的應用,產生應用的實例對象
import { createApp } from 'vue'
//引入App組件(全部組件的父級組件)
import App from './App.vue'

//建立App應用,返回對應的實例對象,調用mount方法掛載到id爲app的DOM中(public文件夾下的index.html)
createApp(App).mount('#app')
  • App.vue
<template>
<!-- Vue2中的html模板必需要有一對根標籤,Vue3組件的html模板中能夠沒有根標籤 -->
  <img alt="Vue logo" src="./assets/logo.png">
  <HelloWorld msg="Welcome to Your Vue.js + TypeScript App"/>
</template>

<!--script標籤能夠設置lang爲ts,支持ts代碼-->
<script lang="ts">

// defineComponent函數,做用是定義一個組件
import { defineComponent } from 'vue';
import HelloWorld from './components/HelloWorld.vue';

//使用defineComponent()對外暴露一個定義好的組件
//函數內部能夠傳入一個配置對象,對象與vue2一致
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>

image.png


3、使用Vue3與vue2經過cli腳手架搭建的項目區別
一、vue2組件中必須有一個根標籤,vue3能夠沒有根標籤
二、vue2實例化使用new Vue(),vue3使用createApp()
三、vue2掛載DOM的方式是使用el屬性,Vue3使用mount()方法傳入DOM選擇器。
四、vue3註冊組件使用defineComponent方法
五、vue3支持TypeScriptvue-cli

相關文章
相關標籤/搜索