Yesterday, I wanted to feel how much fun VUE3 was, so I set up the project step by step according to the tutorial to do a novice experience, but the result was tragic. Only now is an initialization project finally running. Sometimes time is like water flowing east, and if you’re not careful, it’s gone. So trying something new is risky!

  • 📢 welcome to like: 👍 collect ⭐ message 📝 if there are mistakes please correct, give people rose, hand left lingering fragrance!
  • 📢 This article was originally written by Webmote and originally published by Nuggets.
  • 📢 author’s motto: life is toss about, when you don’t toss about life, life will start to toss about you, let us come on together! 💪 💪 💪

1. Enable new VUE3 features

Here simply mention, after all, the official website introduction has been very detailed, I can understand this back-end, visible how clear write.

  • Modular Api
  • Single file component
  • Ts Full support

.

No, if you’re going from VUe2, it’s pretty easy. Just take a look at the new vuE3 features.

All right, let’s start a new project for VUE3.

npm install vue@next
npm install -g @vue/cli
Copy the code

Create a new project using the following commands

# npm 6.x
$ npm init vite@latest <project-name> --template vue

#NPM 7+ requires an extra double dash
$ npm init vite@latest <project-name> -- --template vue

$ cd <project-name>
$ npm install
$ npm run dev
Copy the code

Perform the NPM package installation, run NPM Install, and then run NPM Serve.

Good, the project is done. The classic VUE Web page opens.

So far, so good.

2. Go to the TypeScript project

Since moving to TypeScript, the tragedy has happened…

I searched the tutorials online and started moving my previous project to TypeScript.

Also opened the front end of the project extremely difficult game mode, before and after the deletion of node_module do not know how many times, once let me doubt life, into the extreme closed state.

Yes, nasty front-end environment, it is estimated that every front-end personnel must walk the road to cross the river! Perhaps the most important thing is to go over and look back and realize that it’s not the road or the river at all.

To list a few mistakes:

  • Vue3 does not recognize TS files
  • Uncaught ReferenceError: process is not defined
  • Syntax Error: TypeError: Cannot read property ‘references’ of null
  • Tsconfig. json and tslint.json warning problems
  • Error found in tsconfig.json webpack-env type definition file
  • Ts – loader couldn’t find it

.

Baidu’s brand has been broken by me, and the problems keep coming up, especially after I read the tutorial on vue’s website and typed in Vue Add typescript.

3. Quit/start over

Completely gave up the idea and courage to switch from JS to TS and started again this time.

# 1. Install Vue CLI, if not already installed
npm install --global @vue/cli@next

To create a new project, select the "Manually select features" option
vue create my-project-name

# 3. If you already have a Vue CLI project that does not have TypeScript, add the appropriate Vue CLI plug-in:
vue add typescript
Copy the code

In particular, the second point to create a new project is to select the “Manually select features” option.

The options are shown in the template below:

Created in this way, I also found a problem with my NodeJS version, she is V12 and needs to be upgraded!

Use Choco for Windows to install and upgrade.

choco install nodejs
Copy the code

Generally, the latest version: V17.

Re-create the typescript project, run it, and it’s OK. Alas, once the problem is resolved, it doesn’t matter.

4. Enable multiple environments, API mocks and proxies

Add the environment files.env.dev and.env.prod and write them as follows:

ENV = 'development'
# base api
VUE_APP_BASE_API = '/api'

Copy the code

Modify package.json to add environment support.

{
  "name": "stream-protal"."version": "0.1.0 from"."private": true."scripts": {
    "dev": "vue-cli-service serve --mode dev"."build": "vue-cli-service build --mode prod"."test:unit": "vue-cli-service test:unit"."lint": "vue-cli-service lint"
  },
  "dependencies": {
    "@types/mockjs": "^" 1.0.4."axios": "^ 0.24.0"."core-js": "^ 3.8.3"."element-plus": 6 "" ^ 1.2.0 - beta.."mockjs": "^ 1.1.0." "."vue": "^ 3.2.13." "."vue-class-component": "^ 8.0.0-0"."vue-router": "^ 4.0.3"."vuex": "^ 4.0.0"},... }Copy the code

Modify vue.config.js to add config for development service and config for proxy.

const { defineConfig } = require('@vue/cli-service'); Const name = 'system '; const port = '5001'; Module. exports = defineConfig({transpileDependencies: true, outputDir: 'dist', // publicPath: '/', assetsDir: 'static', productionSourceMap: false, lintOnSave: false, devServer: { host: 'localhost', port: port, open: true, proxy: { // [process.env.VUE_APP_BASE_API]: { // target: `http://localhost:9090`, // changeOrigin: true, // ws: false, // logLevel: 'debug', // // pathRewrite: { // // ['^' + process.env.VUE_APP_BASE_API]: '' // // } // }, '/swagger': { target: `http://localhost:9090`, changeOrigin: true, logLevel: 'debug', }, }, }, });Copy the code

The comment [process.env.vue_app_base_api]: {… The API co-domain proxy. The reason for the comment is to turn on the mock.

Add an open code to main.ts:

if (process.env.NODE_ENV === 'development') {
  require('./mock/index.ts');
}
Copy the code

Mock files are easier to write. As follows:

import Mock from 'mockjs';
import { getApiUrl } from '@/api/baseUrl';
import User from './user/login';

//console.log('api', getApiUrl());
Mock.mock(`${getApiUrl()}/user/login`.'post', User.login);

export default Mock;
Copy the code

User.login is a mock function, so write it yourself.

The API has also been tweaking a bit. Axios is already pretty good, but everyone has different habits, so you can make interceptors and stuff like that.

I’ve encapsulated a generic API access, not all restful, but try to make the front end work without writing so many similar apis.

import Http from './http';

export default class api {
  resource: string;
  http: Http;
  constructor(res: string) {
    this.resource = res;
    this.http = new Http();
  }

  onLoad() {}

  // Get the paging list or the full data list
  getList(params: object) {
    return this.http.fetch(` /The ${this.resource}/GetList`.'post', params);
  }

  / / new
  add(params: object) {
    return this.http.fetch(` /The ${this.resource}/Add`.'post', params);
  }

  // Modify the entity
  update(params: object) {
    return this.http.fetch(` /The ${this.resource}/Update`.'post', params);
  }

  // Batch change
  batchUpdate(ids: any[], params: any) {
    params = params || {};
    params.ids = ids;
    return this.http.fetch(` /The ${this.resource}/BatchUpdate`.'post', params);
  }

  // Delete the specified data
  delete(id: any) {
    const sid = encodeURIComponent(id);
    return this.http.fetch(` /The ${this.resource}/${sid}`.'delete');
  }
  // Batch delete
  batchDelete(ids: any[]) {
    const strIds = ids.join(', ');
    const sid = encodeURIComponent(strIds);
    return this.http.fetch(` /The ${this.resource}/${sid}`.'delete');
  }
  / / to get
  get(id: any) {
    return this.http.fetch(` /The ${this.resource}/${id}`.'get');
  }

  // Get the list of child entities
  getDetail(id: any) {
    return this.http.fetch(` /The ${this.resource}/Detail/${id}`.'get');
  }

  // Subentities are updated in batches, created in batches, modified in batches, committed in batches, deleted in batches
  updateDetail(id: any, params: object) {
    return this.http.fetch(` /The ${this.resource}/Detail/${id}`.'post', params);
  }

  // Get the list of child entities
  login(params: any) {
    return this.http.fetch(` /The ${this.resource}/login`.'post', params); }}Copy the code

Oo, finally, did not put on Github, sorry, there is no time today, butt pain!

5. Summary

Take too many detour, already can’t remember how to walk straight road, vomit blood, weekend is also over, @especially rain stream estimate can’t have what good word, ah, who call I am a novice?

👓 have seen this, but also care about a thumbs-up?

👓 has been liked, but also care about a collection?

👓 are collected, but also care about a comment?