[middle stage] please stay and join me in the backstage

Alex, Cheng 2021-05-03 13:22:48
middle stage stay join backstage


A few words , Series 1 Medium Demo The project will not be a formal project , I'm writing that Demo Project time ,Vue3 I haven't come out yet , stay Vue2.0 It says in it TypeScript It's more troublesome , But by vue-class-component It's not bad to write , Although I have to get familiar with many new things , Increase the psychological pressure, ha ha ha ~~~

Finally ,Vue3 Come out , Natural support TypeScript, We don't have to add so much mental burden any more , No more bullshit , Just roll up your sleeves .

Environment depends on

- node v14.15.1
- npm 7.7.2
- qiankun ^2.4.1
- @vue/cli 4.5.11
- Vue3 ^3.0.0
- Typescript ~3.9.3
- ant-design-vue ^2.0.0
- vue-router ^4.0.4
- vuex 4.0
 Copy code 

Initialize project

adopt vue create project-name Create project

choice Manually select features

choice TypeScript, choice 3.x (Preview)

When initializing a project , It's better to install vue-router and vuex, Because that's what we have to rely on in our project , Otherwise, we need to add it manually in the process of writing !

choice ESLint + Standard config,Lint on save,

choice In dedicated config files, Configure their own information in a dedicated configuration file

choice Save this as a preset for future projects? Yes, Save the configuration as a default for future projects , When you create a project in the future, you can directly select your template .

Last return , Just wait quietly .

The specific configuration is shown in the figure :


After the project is initialized , Open the project and see the following directory structure :


Then let's try to change something :


Here we are Vue3 + TypeScript The project is created .

ant-design-vue 2.0


npm install ant-design-vue@^2.0.0 -S
yarn add ant-design-vue@^2.0.0 -S
 Copy code 

Introduce on demand

install babel-plugin-import plug-in unit

modify babel.config.js

module.exports = {
presets: [
plugins: [
{ libraryName: 'ant-design-vue', libraryDirectory: "es", style: true }
 Copy code 

How to use this.$message

  • Method 1 : Use provide/inject( Used for combinations or options API)
import { message } from 'ant-design-vue'
const app = createApp({ ... })
app.provide('message', message)
 Copy code 

Use in components

import { inject } from 'vue'
setup() {
const $message = inject('message')
 Copy code 
  • Method 2 : Use global configuration globalProperties

Be careful : This only applies to options API.

import { message } from 'ant-design-vue'
const app = createApp({ ... })
app.config.globalProperties.$message = message
 Copy code 

Use in components

mounted() {
this.$message.success('mounted: this.$message.success')
 Copy code 


<a-button @click="$message.error('error!!')"> Popup </a-button>
 Copy code 

Use ant Icon

When you copy an icon and paste it into the code , It's a component , such as question mark Icon <QuestionOutlined />.

You need to get from @ant-design/icons-vue Import .

If not installed , need yarn add @ant-design/icons-vue

Use iconfont Icon

iconfont Official website

First we go to iconfont Official website , Find some icons you like , Store them in your own warehouse .

import { StepForwardOutlined, createFromIconfontCN } from '@ant-design/icons-vue'
// Use iconfont Icon , there url It's your collection iconfont project js route 
const IconFont = createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/font_2299454_fvw4ct8o61.js'
// Partial registration IconFont
components: { IconFont }
// Global registration 
export default {
// App yes vue example The type of 
install: (app: App, options: InstallOptions = defaultInstallOpt ) => {
app.component('icon-font', IconFont)
AntdComponent.forEach(comp => {
app.component(comp.name, comp)
 Copy code 

Using icons

<div class="icon-list">
<icon-font type="icon-mugua"></icon-font>
<icon-font type="icon-caomei"></icon-font>
<icon-font type="icon-xigua"></icon-font>
<icon-font type="icon-yingtao"></icon-font>
<icon-font type="icon-douya"></icon-font>
<icon-font type="icon-xianggu"></icon-font>
<icon-font type="icon-angel"></icon-font>
<style scoped lang="less">
.icon-list {
padding: 2em 0;
:deep(.anticon) {
font-size: 36px;
margin-right: .5em;
 Copy code 

The effect is as follows .


vue-router 4


Use npm perhaps yarn

npm install vue-router@4 -S
yarn add vue-router@4 -S
 Copy code 


createRouter Function to create a function that is Vue Examples used by applications .Options Used to initialize router.

createWebHistory Create a HTML5 history , The most common history in single page applications . That's the previous version of mode : history. Another common hash Pattern , stay v4 Used in createWebHashHistory. The usage in routing table is the same as before .

// router/index.ts
export default createRouter({
history: createWebHistory(),
routes: constantRoutes
 Copy code 

however , stay composition api We all passed setup Hook as a combination API Entrance , It's unusable inside this Of , But in the template Can be used in $router perhaps $route.

So how do we route programmatically as before this.$router perhaps this.$route Well ?

Use useRouter and uesRoute

import { useRouter, useroute } from 'vue-router'
setup() {
const router = useRouter()
const store = useStore()
 Copy code 

Other Router Api Just go to the official website .

Vuex 4.0


Use npm perhaps yarn install

npm install vuex@next --save
yarn add vuex@next --save
 Copy code 


establish store/index.ts file , from vuex Import createStore To create our store example , Don't forget to use it after you write the content vue To register .

// store/index.ts
import { createStore } from "vuex"
// Define the type of storage state 
export interface State {
count: number
// If not 'State' Interface to 'createStore' in , stay 'mutations' Used in state It's supposed to be 'unknown' type 
const store = createStore<State>({
state() {
return {
count: 0
mutations: {
increment(state) {
export default store
 Copy code 

register store

// main.ts
const app = createApp({ /* your root component */ })
 Copy code 

When we need to use stay store As defined in count when , Find out count The type is any


When we're in Composition API Written in Vue When the component , It's likely that useStore Returns typed storage . In order to make useStore Return the input storage correctly , The following steps must be done :

1. Define typed `InjectionKey`.
2. stay `Vue` Install... In the application `store` Provides typed `InjectionKey`.
3. Put typed `InjectionKey` Pass to `useStore` Method .
 Copy code 

go back to store/index.ts file ```ts import { InjectionKey } from "vue" import { createStore, Store } from "vuex"

// Define injection key
export const key: InjectionKey<Store<State>> = Symbol()
 Copy code 

Then we can put key Pass to useStore Method to retrieve typed storage , It can be pushed out correctly where it is used state.count The type of .



stay A series of It has been introduced in this paper qiankun and Microfront The concept of , There's no more verbosity here .


yarn add qiankun@2.4.1 -S
 Copy code 


although Series 1 The usage has been written in , But it's still a little different in the project that started , So here we're going to see how to Vue3 Use it in .

Now we still take a small chestnut as the entrance , To learn how to use it .

First of all we have src Next, create a new file single-spa.ts file , To handle connections Subapplication Configuration of , The code is simple , Go straight to the code , It describes some key information .

import {
} from "qiankun"
const apps = [
name: 'vue3-base', // apply name 
entry: '//localhost:8080', // Application entry , Resource path 
container: '#subAppContainer', // Store... In the main body Subapplication The container of id
activeRule: '/vue-base', // Switch the specified subapplication according to this rule , Activation rules 
props: {
// Data passed to the subapplication 
user: {
age: 18
const excutorSingleSpa = () => {
registerMicroApps(apps, {
beforeLoad: [
// @ts-ignore
app => {
console.log(' Print before loading the app apps', app)
addGlobalUncaughtErrorHandler((event: Event | string) => {
const { message: msg } = event as any
// Prompt when loading fails 
if (msg || msg.includes("died in status LOADING_SOURCE_CODE")) {
console.error(" Micro application loading failed , Please check if the app is runnable ", msg);
// Whether to turn on preloading , The default is true.
// Configure to true In the first micro application mount After that, start to preload the static resources of other micro applications 
prefetch: false,
sandbox: true
export default excutorSingleSpa
 Copy code 

In terms of project structure , We usually have one layouts.vue Components , There is an area to render our routing pages . And ours Subapplication It's also rendered here .

// layout/index.vue
// Other structures are omitted
:style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
<!-- Main content rendering section -->
<!-- Sub application rendering part -->
<div id="subAppContainer"></div>
 Copy code 

stay layout/index.vue In file , We introduce single-spa.ts file .

import useSingleSpa from '@/single-spa'
setup() {
 Copy code 

And then we were in router/index.ts in , Join in Subapplication Menu for .

// routes
import { RouterView } from 'vue-router'
const routes = [
// Omit other routes 
path: '/vue-base',
component: Layout,
children: [
path: 'home',
// `RouterView` Shows the current route , Just follow `<router-view />` equally .
// We might have written that before component: h => h('router-view')
component: RouterView,
path: 'about',
component: RouterView,
 Copy code 

Come here , The main project is almost ready . Then configure Subapplication .

Sub application configuration

If you do Series 1 , You know we don't need to install any dependencies in the subapplication , Only need main.ts These hook functions are derived from bootstrap,mount,unmount.

Let's see how to configure the routing of the subapplication .

The root directory here '/' It's relative to subapplication , Because through createWebHistory('/vue-base') Set the route prefix , It's going to be /vue-base , And then redirect to /vue-base/about

// router/index.ts
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/Home.vue'
const routes: Array<RouteRecordRaw> = [
path: '/',
redirect: '/about'
path: '/home',
name: 'Home',
component: Home
path: '/about',
name: 'About',
// Road load by lazy 
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
const router = createRouter({
// Detect how it is rendered by the host , Just add `/vue-base` Route prefix , In order to distinguish the main and sub application routing 
history: window.__POWERED_BY_QIANKUN__ ? createWebHistory('/vue-base') : createWebHistory(process.env.BASE_URL),
export default router
 Copy code 

Sub application of App.vue The structure is as follows

<div class="app">
<div id="nav">
<router-link to="/home">Home</router-link> |
<router-link to="/about">About</router-link>
<!-- Render matching routes component -->
 Copy code 

And then we create vue.config.js, To deal with it Subapplication Problems that may arise in embedding the subject project .

const { name } = require('./package.json')
module.exports = {
devServer: {
headers: {
"Access-Control-Allow-Origin": "*"
configureWebpack: {
output: {
library: `${name}-[name]`,
libraryTarget: 'umd',
jsonpFunction: `webpackJsonp_${name}`
 Copy code 

Come here , Our subapplication vue-base Just configure it .

Let's see the effect !

Now the interface is The main body First page of the project .


This interface , Just click Navigation vue-base Next page .


Come here , Our subapplication and main body are linked together , After the project iterations , It's going to get more and more complicated .

Communicate together

If you like this part , Just join us QQ Group , Let's share technology with you ~

本文为[Alex, Cheng]所创,转载请带上原文链接,感谢

  1. Why did gitlab choose vue.js?
  2. HTTP-RPC: 轻量跨平台REST服务
  3. 继全面采用Node.js以后,PayPal分享大幅度踩坑GraphQL心得 - Mark Stuart
  4. vue组件化开发实战之滚动/轮播的实现
  5. Http-rpc: lightweight cross platform rest Service
  6. Following the full adoption of node.js, PayPal shares a great deal of graphql experience mark Stuart
  7. Implementation of rolling / carousel in Vue component development
  8. CSS是什么?这一篇全解,绝对有你想要的
  9. What is CSS? This is a complete solution, there is absolutely what you want
  10. 04-HTML5常用标签-HTML5极速入门
  11. 04-html5 common tags
  12. WEB前端全套零基础视频教程+软件2021最新编程视频
  13. Web front end full set of zero basic video tutorial + software 2021 latest programming video
  14. 使用Node, Mongo, React, Redux实现Token认证
  15. Using node, Mongo, react and Redux to realize token authentication
  16. 体面编码之CSS和HTML
  17. CSS and HTML for decent coding
  18. 使用Playwright基于多浏览器进行javascript自动化测试的简单教程- Applitools
  19. A simple tutorial for JavaScript automatic testing based on multi browser using playwright - applitools
  20. Minimum distance to target element
  21. 浅谈 React 中的 XSS 攻击
  22. XSS attack in react
  23. 自学前端教程整理,附不容错过的前端100篇文章合集
  24. Self taught front-end tutorial collation, with a collection of 100 front-end articles that can not be missed
  25. 使用OpenTracing跟踪Go中的HTTP请求延迟
  26. Using opentracing to track HTTP request latency in go
  27. Encapsulating databinding allows you to write less than 10000 lines of code
  28. 03-HTML5标签-HTML5极速入门
  29. 03-html5 tag-html5 quick start
  30. LayUI - 极易上手拿来即用的前端 UI 框架
  31. Layui - easy to use front end UI framework
  32. Interpretation of lodash source code (1)
  33. Why is the first parameter of node family callback error?
  34. 报告:JavaScript 开发者达1380 万,C#超越 PHP,Rust 增长最快
  35. Report: Javascript developers reach 13.8 million, C surpasses PHP, and rust grows fastest
  36. 小白前端入门笔记(10),怎么设置网站内部的超链接?
  37. How to set up hyperlinks inside the website?
  38. Using node and socket to realize online chat room
  39. The core competitiveness of Vue: data bidirectional binding
  40. React configuration agent
  41. CSS layout
  42. Application scenario explanation of Vue dynamic component
  43. Redux learning notes 04 -- using multiple reducers to manage data
  44. After three months of typescript writing, what have I learned?
  45. Node family - what is a callback?
  46. React -- a simple implementation of render & create element
  47. JS learning simple usage of jquery
  48. Seamless love
  49. 小白前端入门笔记(12),设置哑链接
  50. Small white front-end entry notes (12), set dumb links
  51. Vue2. X opens composition API and TSX
  52. Interview record and thinking of social recruitment for one and a half years (Alibaba, Tencent, baidu offer)
  53. Flex learning notes
  54. The most essential closure article in the eastern hemisphere
  55. 2021-05-03 hot news
  56. Sword finger offer -- reverse order pair in array (JS Implementation)
  57. Working process of scaffold
  58. Use decorator mode to strengthen your fetch
  59. [JS] scope (Introduction)
  60. Employment information statistics network (interface document)