1. 开发环境的搭建

在官网下载Node.js运行环境:

https://nodejs.org/zh-cn/

安装yarn工具:

npm install -g yarn

安装vue3

yarn global add vue@next

或使用Vue CLI

yarn global add @vue/cli
vue upgrade --next

2. 项目的创建

创建一个vue项目

vue create jsadmin

选择手动配置特征:

Vue CLI v4.5.13
? Please pick a preset: (Use arrow keys)Default ([Vue 2] babel, eslint)Default (Vue 3) ([Vue 3] babel, eslint)
> Manually select features

通过↑↓移动并使用空格键勾选需要的内容后回车:

Vue CLI v4.5.13
? Please pick a preset: Manually select features
? Check the features needed for your project:(*) Choose Vue version(*) Babel(*) TypeScript(*) Progressive Web App (PWA) Support(*) Router(*) Vuex(*) CSS Pre-processors
>(*) Linter / Formatter( ) Unit Testing( ) E2E Testing

在上面可以额看到我们选用了CSS预处理器、TypeScript、Router前端路由器、Vuex等等。
使用vue3:

Vue CLI v4.5.13
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, TS, PWA, Router, Vuex, CSS Pre-processors, Lint
er
? Choose a version of Vue.js that you want to start the project with2.x
> 3.x
? Use class-style component syntax? Yes
? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? (Y/n) Yes

路由历史模式选择No,这样你SPA路由会出现"/#/"(看起来比后端路由丑),不过编译后的项目不需要一个后端服务也可以打开。

? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) No

根据的你的技术栈或习惯,选择你所使用的CSS预处理器:

? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): (Use arrow keys)
> Sass/SCSS (with dart-sass)Sass/SCSS (with node-sass)LessStylus

完成接下来的配置

? Pick a linter / formatter config: (Use arrow keys)
> ESLint with error prevention onlyESLint + Airbnb configESLint + Standard configESLint + PrettierTSLint (deprecated)
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
>(*) Lint on save( ) Lint and fix on commit
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
> In dedicated config filesIn package.json
? Save this as a preset for future projects? (y/N)

然后脚手架将自动帮助你完成接下来的项目构建,构建完成后使用cd进入到你的项目文件夹。

3. 开始你的项目

接下来,为你的项目来安装一些前端库:

yarn add bootstrap -D
yarn add @popperjs/core@^2.10.2 -D
yarn add webpack@^4.36.0 -D
yarn add echarts -D
yarn add element-plus -D
yarn add axios -D
yarn add vue-axios -D

4. Vue3 全局参数的挂在和使用

4.1 挂载全局参数

一些Vue3教程把Vue上的主要改变仅仅放在组合式API、响应式数据等内容上但对Vue使用方式的颠覆性改动置若罔闻这无疑是本末倒置,因为在实际使用时,这就带来了很大的不同。
如果你试图使用vue2中的方法在main.js直接对Vpp实例在其原型链上绑定某些对象或者参数,比如axios,那么很遗憾,你必定是徒劳的。在vue3 的组件中,this不再指向Vue全局对象,并且Vue3中也不再直接使用Vue对象,取而代之的是createApp。如果想要全局挂载一个对象必须使用Vue3特别提供的config.globalProperties。实现。
在以前使用Vue2时,你大概会这样做:

// main.js,省略其他代码
import Vue from "vue";
import axios from "axios";Vue.prototype.$axios = axios;

不过,打开Vue3的main.ts后你看到的初始内容时这样的:

import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'createApp(App).use(store).use(router).mount('#app')

为了更改方便,我们将最后一行改为如下:

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

vue3中取消了Vue,组件中this也不指向Vue。完全就不再有“Vue”,怎么办呢?

Vue3 中的全局参数需要在`app.config.globalProperties`注册

以axios为例:

import { createApp } from 'vue'
import VueAxios from 'vue-axios'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'import axios from 'axios'
axios.defaults.baseURL = '/api'         const app = createApp(App)
app.config.globalProperties.$rqst= axios  app.use(VueAxios, axios)
app.use(store)
app.use(router)
app.mount('#app')

4.2 在vue组件中(或视图等)使用全局参数

在Vue2中,如果你想使用一个在Vue原型链中挂载的全局参数,可以直接使用this。比如:

// main.js,省略其他代码
Vue.prototype.pram = "pram";
// 某组件的script,省略其他代码
export default {name: "cmpnt",methods: {logPram() {console.log(this.pram);}}
}

而在Vue3中则需要使用到getCurrentInstance

// main.ts,省略其他代码
const app = createApp(App)
app.config.globalProperties.pram= "pram";
// 某组件的script,省略其他代码
import { defineComponent, getCurrentInstance} from 'vue';
export default defineComponent({name: 'Xxx',setup() {const { proxy } = (getCurrentInstance() as any);     // 全局对象代理console.log(this.proxy.pram);                        // 获取某个已经绑定的全局参数return {}},
});

5. 在Vue3中配置和使用axios

5.1 全局引入axios对象示范

main.ts

import { createApp } from 'vue'
import VueAxios from 'vue-axios'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'import axios from 'axios'                   // 引入axios
axios.defaults.baseURL = '/api'             // 之后我们用作代理的utlconst app = createApp(App)
app.config.globalProperties.$rqst= axios    // vue3 中的全局参数需要在`app.config.globalProperties`下挂载
app.use(VueAxios, axios)
app.use(store)
app.use(router)
app.mount('#app')
// 可以合并为 app.use(VueAxios, axios).use(store).use(router).mount('#app')

5.2 配置代理服务器示例

在项目的更目录下创建vue3配置文件vue.config.js,添加以下内容

module.exports = {/* webpack-dev-server 相关配置 */devServer: {/* 代理配置 */proxy: {'/api': {target: 'http://8.129.172.130:80/',    // 目标代理服务器地址changeOrigin: true,                    // 允许跨域pathRewrite:{"^/api":''}},},},
}

5.3 Vue3中使用axios发起请求示例

这里使用的axios对象时按照上文中使用的方法进行全局绑定的。以下是某个组件或者视图的.Vue文件的一对<sctips>标签中:

import { defineComponent, getCurrentInstance, reactive, ref } from 'vue';
import Header from '@/components/Header.vue';
import MCode from "@/components/MonacoCode.vue"
import LeftBar from "@/components/LeftBar.vue"export default defineComponent({name: 'Xxx',setup() {const { proxy } = (getCurrentInstance() as any);return {proxy,}},created: function () {this.getBillsList("Jack");},methods: {getBillsList(user:string){this.proxy.$rqst.post('/bill/getBillsList',{"user":user}).then((response: any)=>{console.log(response.data);}}}}
});

6. 在项目中添加常用库

6.1Vue3中配置使用elementUI

要在Vue3+TypeScript的环境中使用elementUI需要安装element-plus,在上面我们已经安装过了,这里不再重复。

// main.ts,已省略其它内容
import installElementPlus from './plugins/element'const app = createApp(App)
installElementPlus(app)

6.2. Vue3中配置echarts示例

在上面我们已经安装过echarts了,这里不再重复安装过程。

6.2.1 封装一个通用vue-echarts基本组件

echarts是绑定id来渲染图形的,如果出现相同的id号则部分echarts图形会出现错误。这里我们通过时间戳来简单地产生不同id,使得在一个vue项目多次使用echarts图表时不用人为地去关系id,只需要考虑图标本身的option。
src\components下新建一个Echarts-base.vue组件文件,输入以下内容:

<template>
<div class="chartsbox"><div :id="echats_id" :style="{width:width, height:height}" />
</div></template><script lang="ts">import { defineComponent, ref } from 'vue';
import * as echarts from 'echarts';export default defineComponent({props: {datas: {type: Object,default: function(){return {width: "300px", height: "200px",option:{}}}}},setup(props) {let tm = new Date().getTime().toString();  // 获取格林威治时间let randomnum = (1000000*Math.random()).toString();let echats_id = "echarts" + tm.slice(5,)+ randomnum.slice(0,5); console.log(echats_id);let datas = (props as any).datas;let option = ref(datas.option);let width = datas.width;let height = datas.height;return{echats_id,option,width,height}},mounted() {let myChart = echarts.init(document.getElementById(this.echats_id) as HTMLElement);myChart.setOption(this.option);},
});</script><style lang="scss">.chartsbox{width: 100%;display: flex;align-items: center;justify-content: center;
}</style>

6.2.2 通过 vue-echarts基本组件 派生其他echarts组件

示例如下:

新建一个Line.Vue文件,添加以下内容:

<template><Charts class="LineChart" :datas="lineDatas" />
</template><script lang="ts">import { defineComponent } from 'vue';
import Charts from '@/components/Charts.vue';
export default defineComponent({name: 'Ctline',props: {datas: {type: Object,default: function(){return {option:{},x:[],y:[]}}},},setup(props){let getDatas = (props as any).datas;let lineDatas;if(getDatas.option!==undefined){lineDatas = getDatas.option}else{lineDatas = {width: getDatas.width,height: getDatas.height,option:{title: {text: getDatas.title,x:'center',y: 'top',},grid: {top:'10%',left: '3%',right: '4%',bottom: '3%',containLabel: true},xAxis: {type: 'category',data: getDatas.x},yAxis: {type: 'value'},series: []}}}return{lineDatas}},components: {Charts,},
});</script><style scoped lang="scss">.LineChart{width: 100%;height: 300px;
}</style>

6.3. Vue3+TypeScript环境中使用bootstrap

在上面我们已经安装过echarts了,这里不再重复安装过程。

bootstrap的引入

在组件或者试图(.vue)的脚本部分添加以下内容即可:

import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

6.4. Vue3中使用代码高亮插件highlight示例

安装highlight.js,略。
main.ts中添加以下内容:

// main.ts,省略其他代码
import hljs from 'highlight.js'// 以下是安装`highlight`后,部分开箱即用的风格样式css文件,选择一个引入即可。你一可以自己编写一个CSS样式引入
// import 'highlight.js/styles/monokai-sublime.min.css'
// import 'highlight.js/styles/foundation.min.css'
// import 'highlight.js/styles/kimbie-dark.min.css'
// import 'highlight.js/styles/idea.min.css'
// import 'highlight.js/styles/idea.min.css'
// import 'highlight.js/styles/hybrid.min.css'
// import 'highlight.js/styles/nnfx-dark.min.css'
// import 'highlight.js/styles/nnfx-light.min.css'
// import 'highlight.js/styles/nord.min.css'
// import 'highlight.js/styles/vs2015.min.css'
// import 'highlight.js/styles/vs.min.css'
// import 'highlight.js/styles/xcode.min.css'
// import 'highlight.js/styles/magula.min.css'
// import 'highlight.js/styles/paraiso-dark.min.css'
// import 'highlight.js/styles/paraiso-light.min.css'
// import 'highlight.js/styles/purebasic.min.css'
// import 'highlight.js/styles/github.min.css'
// import 'highlight.js/styles/googlecode.min.css'
// import 'highlight.js/styles/color-brewer.min.css'
// import 'highlight.js/styles/codepen-embed.min.css'
// import 'highlight.js/styles/a11y-dark.min.css'
// import 'highlight.js/styles/a11y-light.min.css'
import 'highlight.js/styles/dark.min.css'const app = createApp(App)
// 注册自定义指令高亮代码
app.directive('highlight', {// Directive has a set of lifecycle hooks:// called before bound element's parent component is mountedbeforeMount(el:any) {// on first bind, highlight all targetsconst blocks = el.querySelectorAll('pre code');for(let i = 0 ;i < blocks.length ; i++){const item = blocks[i]// console.log(item)hljs.highlightBlock(item)}},// called after the containing component's VNode and the VNodes of its children // have updatedupdated(el:any, binding:any) {// after an update, re-fill the content and then highlightconst targets = el.querySelectorAll('code');for (let i = 0; i < targets.length; i += 1) {const target = targets[i];if (typeof binding.value === 'string') {target.textContent = binding.value;}hljs.highlightBlock(target);}}
})

7. 路由设计

在上文中我们使用Vue官方脚手架(命令行工具、Command Lines、CLI)构建Vue项目时,选择使用了Vue Router,它就是用来使用前端路由的。由于没有使用history模式,作为SPA的路由子地址将在根露路由后以/#/方式呈现。
项目根路由router/index.js是在项目初始化时自动生成的:

其内容如下:

import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/Home.vue'const routes: Array<RouteRecordRaw> = [{path: '/',name: 'Home',component: Home},{path: '/about',name: 'About',// route level code-splitting// this generates a separate chunk (about.[hash].js) for this route// which is lazy-loaded when the route is visited.component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')}
]const router = createRouter({history: createWebHashHistory(),routes
})export default router

在这个文件中定义了两个路由。其实际url为 主机IP地址/端口号+path。当在本机上运行8080端口时(ip为本地回环地址127.0.0.1)

  • 第一个路由path: '/'对应url:http://127.0.0.1:8080/,当用户请求该地址时,将渲染视图“../views/Home.vue'
  • 第二个路由使用了路由懒加载,也就是仅仅到了该路由是才会实际渲染它。届时将渲染路由'/about'到路由组件'../views/About.vue'

路由是做什么?

  • 路由就是将特定的 url视图(views)进行绑定

嵌套路由

const router = new VueRouter({routes: [{path: '/user/:id',component: User,children: [{// 当 /user/:id/profile 匹配成功,// UserProfile 会被渲染在 User 的 <router-view> 中path: 'profile',component: UserProfile},{// 当 /user/:id/posts 匹配成功// UserPosts 会被渲染在 User 的 <router-view> 中path: 'posts',component: UserPosts}]}]
})

children 配置就是像 routes 配置一样的路由配置数组,所以呢,你可以嵌套多层路由。以 / 开头的嵌套路径会被当作根路径。 这让你充分的使用嵌套组件而无须设置嵌套的路径。

8. 编写视图

视图就是对应于路由的内容

10. 构建为可直接在浏览器打开的单页面html

这是很有意义的一件事,尤其是在进行安卓、iphon手机开发移动页面时,我们考虑使用webView来进行移动端页面设计。
打开vue3配置文件vue.config.js,添加以下内容:

  //  部署应用包时的基本 URL。/*默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上,例如 https://www.my-app.com/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://www.my-app.com/my-app/,则设置 publicPath 为 /my-app/。这个值也可以被设置为空字符串 ('') 或是相对路径 ('./'),这样所有的资源都会被链接为相对路径,这样打出来的包可以被部署在任意路径.*/publicPath: './',// 当运行 vue-cli-service build 时生成的生产环境构建文件的目录,// 注意目标目录在构建之前会被清除 (构建时传入 --no-clean 可关闭该行为)。outputDir: 'dist',// 放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录。assetsDir:"statics",//指定生成的 index.html 的输出路径 (相对于 outputDir)。也可以是一个绝对路径。indexPath:"index.html",// 生产环境是否生成 sourceMap 文件productionSourceMap: process.env.NODE_ENV !== 'production'? false : true,

你可以使用以下命令进行构建:

yarn build

或者:

npm run build

构建完成后,在你的项目中多了一个dist目录 ,里面就是你构建好的一个单页面应用了。它包含了一个index.html和其相应的静态文件与js文件。

11. 关于可选配置文件

请参考:
VUE-CLI可选的配置文件 vue.config.js

完成一个Vue3项目的过程相关推荐

  1. 【Vue】新建一个Vue3项目

    目录 1.新建vue项目 2.路径更改至新建的vue项目处 3.安装cnpm 4.cnpm安装vant3 5.安装babel-plugin 6.安装vue路由 7.安装axios 其他注意事项 仅用于 ...

  2. eclipse 创建maven web项目_Eclipse创建第一个Scala项目(过程)

    安装JDK,我已经安装好了,如果不会安装搜索之前的文档<Win10+Java1.8环境搭建(图解教程)> 安装Maven,我已经安装好了,如果不会安装搜索之前的文档<Eclipse配 ...

  3. 搭建一个简单的vue3项目

    vue3项目的创建 环境准备 nodejs vscode 在正式开发之前,我推荐使用 VS Code 的官方扩展插件 Volar,这个插件给 Vue 3 提供了全面的开发支持.我们可以在vscode里 ...

  4. 使用vite创建vue3项目

    一.创建vite+vue项目 1.在命令行输入以下创建语句.然后根据下图所示,输入项目名称并选择vue框架即可 npm create vite@latest 创建完项目后,根据提示依次输入三条命令: ...

  5. 如何真正的吃透一个Java项目?

    如何真正的吃透一个Java项目?这里要说吃透一个Java项目的标准就是:下次遇到此类Java项目可以快速使用写过的Java项目的解决方案完成它. 要达到这个的标准,还得从开发一个Java项目的过程来分 ...

  6. 【Parcel 2 + Vue 3】从0到1搭建一款极快,零配置的Vue3项目构建工具

    前言 一周时间,没见了,大家有没有想我啊!哈哈!我知道肯定会有的.言归正传,我们切入正题.上一篇文章中我主要介绍了使用Vite2+Vue3+Ts如何更快的入手项目.那么,今天我将会带领大家认识一个新的 ...

  7. 推荐一个 Vue3 全家桶 + TS+ Vite2 + element-plus 的网站实战项目

    五一期间,花了 3 天时间,边学 Vue3 和 Vite2,边重构自己的项目,终于都用 Vue3 + TypeScript + Vite2 + Vuex4 + Vue-Router4 + elemen ...

  8. php 大型系统开法流程图,有一个php项目源码,如何搞清楚执行过程?画出其流程图...

    比如一个c项目,可以让其运行起来,然后利用gdb调试,一步步执行,搞清楚其执行过程,那么一个php项目,如何才能搞清楚执行过程呢,或者需要什么专业的工具 如果你想调试的话,可以使用zend studi ...

  9. 使用IDEA搭建一个简单的SpringBoot项目——详细过程

    一.创建项目 1.File->new->project: 2.选择"Spring Initializr",点击next:(jdk1.8默认即可) 3.完善项目信息,组名 ...

最新文章

  1. 训练集(train set) 验证集(validation set) 测试集(test set)
  2. 华为nova5ipro的优缺点_华为nova5pro和nova5i的区别
  3. socket阻塞导致拿不到信息
  4. 2013\Province_Java_C\2.组素数
  5. 为什么需要Redis 集群
  6. 这 30 个常用的 Maven 命令你必须熟悉
  7. 集合拷贝通用方法、list<A> 转换成 list<B> (属性相同)
  8. transformer中attention计算方式_Reformer: 局部敏感哈希、可逆残差和分块计算带来的高效...
  9. python开发gui实战_python实战GUI界面+mysql
  10. keil删除工程_RTT 是如何管理和构建工程的?
  11. 从浏览器启动客户端程序的方法
  12. 7个等级 容灾等级_猫奴的10个等级 你的奴性有多高?
  13. svn使用方法以及使用教程
  14. pdf复制json不全的问题
  15. 杭电OJ 1046(C++)
  16. 打散线条lisp_《湘源修建性详细规划CAD系统》用户使用手册.doc
  17. leetcode 5390. 数青蛙(C++)
  18. mysql多表查询去重复数据_SQL重复记录查询 查询多个字段、多表查询、删除重复记录的方法...
  19. 硬件选型之如何看光耦器件的开关频率
  20. MaaS无缝出行服务呼之欲出 传统出行模式将被颠覆

热门文章

  1. 【重点】剑指offer——面试题53:正则表达式匹配
  2. Leetcode 15.三数之和
  3. PTA--03-树2 List Leaves
  4. Ubuntu 16.04中的Grub更新警告
  5. __builtin_popcount
  6. React-引入图片的方法
  7. 使用js生成条形码以及二维码
  8. Django学习笔记5-url
  9. vue具体页面跳转传参方式
  10. 机器学习系列——随机森林(五)