Project Background:

A previous project (
I wrote it in my first internship, using Vuecli2), and this time to add changes, look at the code head, impulsive refactoring (
Trying to beat himself to death), just in case you forget to go back to typescript later, starting with build and documenting it step by step. (
BTW, it’s a little awkward to use, but it’s cool. Looking forward to Vue3.0…)

     

I. Project Construction:

  1. Create the project using the command vue create news
  2. Configure custom, post my custom installation dependencies




Ts +vuex+ Router are definitely required. Here I choose SCSS for CSS, and unit test is also required

And then some of the choices are self-selecting

3. This is what the directory looks like

├ ─ ─ the public// Static pages├ ─ ─ the SRC/ / home directory├ ─ ─ assets// Static resources├ ─ ─ the components/ / component├ ─ ─ views/ / page├ ─ ─ App. Vue// Main page entry├ ─ ─ the main ts// The main entry├ ─ ─ the router. Ts/ / routing├ ─ ─ shims - TSX. Which s// Related TSX module injection├ ─ ─ shims - vue. Which s// Vue module injection└ ─ ─ store. Ts/ / vuex configuration├ ─ ─ tests// Test case├ ─ ─. Eslintrc. Js// eslint related configurations├ ─ ─ gitignoreGit ignores file configuration├ ─ ─ Babel. Config. Js/ / the Babel configuration├ ─ ─ postcss. Config. Js/ / postcss configuration├ ─ ─ package. Json/ / rely on└ ─ ─ tsconfig. Json/ / ts configurationCopy the code

I modified the directory structure for better maintenance

├─ public // Static Page ├─ SRC // Home Directory ├─ API // Interface ├─ Assets // Static Resources ├── filters // Filter ├─ store // Vuex Config ├─ styles // Style ├─ Utils // Tool Methods ├─ views // Page ├─ app.vue // page Main import ├─ main.ts // Main import ├─ Router.ts // Route ├─ local.d.ts // Related Global or plugin ├─ Shims-Vue.d.ts // Some TSX modules have been added to the system. Make TypeScript support *.vue files ├─ tests // Test Cases ├─.eslintrc.js // ESLint related Configuration ├─ postcss.config.js // PostCSS Configuration ├─ .gitignore // gitignore File Setup ├── Bass.config. js // Preset Record ├─ package.json // Rely On ├─ readme.md // Project README ├─ Json // tsconfig ├ ─ ├.config.js // webpackCopy the code

Tsconfig. js is the ts configuration item

Specific can see the website configuration: www.tslang.cn/docs/handbo…

4. Modify vue.config.js

const path = require("path");
const webpack = require('webpack');

function resolve(dir) {
  return path.join(__dirname, dir)
}
const router='http://xxx.xxx.xxx'

module.exports = {
  publicPath: ". /"// Base path outputDir:'dist', // lintOnSave: process.env.node_env ==='development',  
  productionSourceMap: process.env.NODE_ENV === 'development', 
  devServer: {
    port: 8080,
    open: true,
    proxy: {
      '/test': {
        target: router,
        changeOrigin: true
      }
    }
  },
  configureWebpack: {
    name: process.env.VUE_APP_NAME,
    resolve: {
      alias: {
        The '@': resolve('src'),
      }
    },
    externals: {},
    plugins: [],
  },
}Copy the code

At this point, the initial construction of the project is complete, and then the package installation plug-in begins

Install the plug-in and fill the basic content

Here I use Element-UI, Echarts, Babel-Polyfill,jquery, etc

One important thing to note is that when using jquery, Echarts, etc., in typescript, you have to install the corresponding declaration file. Of course, the typescripe community has a lot of people who have already written thisCopy the code

What is a declaration file:

Github.com/xcatliu/typ…

Declaration file search address: Microsoft. Making. IO/TypeSearch /


  • Untils folder (you can put some common utility functions, throttling, anti-shake, localStorage, etc.)


  • Styles folder (holds global SCSS files)

In addition to initializing some styles, I also defined some steady lights, such as the height and color of the navigation bar, for easy change

  • Router folder (lazy loading)

 /* webpackChunkName: "login"*/ /* The name of the package is the name of the package */ {path:'/',
    name: 'login',   
    component: () => import(/* webpackChunkName: "login"* /'@/views/login/index.vue'),
    meta: {
      title:'Login page'
      keepAlive: false,
    }
  },
  {
    path: "/home",
    name: "home",
    redirect: "/homepage",       
    component: () => import(/* webpackChunkName: "home"* /"@/views/Home.vue"),
    children: [
      {
        path: "/homepage",
        component: () => import(/* webpackChunkName: "homepage"* /"@/views/homepage/index.vue"),
        name: "homepage",
        meta: {
          title: "Home page", keepAlive: true]}}},Copy the code

  • API folder

Build different files according to the interface of different modules

Typescript in Vue

Typescript is written in much the same way as Vue, except that it differs from Script.

import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
@Component({  
    name: 'homepage', 
    components: {}
})

export class MyComponent extends Vue {  
 @Prop({ default: ' ' }) privatename! :string 
 @Watch('name', { deep: true })  
 changeName(newVal,olVal){}

   //data
   private count:number=5
   private arr:string[]=[]
   mounted(){}

   //methods
    private test(){}
}Copy the code

Problems with typescript use

1. Obtain refs

Writing:

let layoutList:any = this.$refs.layout as HTMLDivElementCopy the code

2. The plug-in is referenced, and the declaration file or reference Json file cannot be found

Declared in the shims-vue.d.ts file and referenced in the component

declare module "*.json" { 
    const value: any;  
    export default value;
}
declare module "vue-count-to" {  
    const count: any;  
    export default count;
}Copy the code

Inside the page

import * as myJson from '.. /.. /.. /public/test.json'Using myJson. DefaultCopy the code

3. Calculate attributes

get  age() { 
    return this.aTagDatasF.filter(item => item.visible)
}Copy the code

4.@prop

@Prop()private datas! The: any exclamation point is a non-null and non-undefined type assertion, so this is a non-null assertion for datasCopy the code

5. When importing vue components, add.vue to the end

6. Define the interface type and add I before it. For example, try to define the interface type and standardize management

interface IUserInfo{
   name:string,
   index:number
}Copy the code

7. Define global variables (vuex can be used instead)

It’s in the.ts file

export var User:IUserInfo={    
    name:'111',
    index:996
}Copy the code

Other pages import, and then you can get this value

8. Force TS not to detect

//@ts-ignore does not check the next line


5. Start reprogramming your page code (Start poking fun at yourself)

Slot 1: Component switchover

Previous code (partial snippets)



Component is used for dynamic judgment

<div class="haveClick>
   <component :is="echartsIndex" :obj="obj"/>
</div>Copy the code


Slot 2: Object assignment

Previous code (partial snippet) :



After transforming:

// This is done because initObj has other keys

for(let i in this.obj){
   if(this.initObj(i)! =undefined) {this.initObj[i]=this.obj[i]
   }
}

/ / orWrite a function that assigns the same key valueCopy the code


Slot 3: Indicates the switch case judgment

Previous code:

// There are dozens of fragmentscase

optionList:['pie'.'Bar chart'.'Line chart'.'... '] index switch (aa) {case 0:  this.getData() break;
       case 1:  this.avgBqzs() break;
       case 2:  this.areaCount() break;
       case 3:  this.yiqing() break;
       case 4:  this.avgFinish() break;
  }Copy the code

Revised:

private optionList=[{
   title:'pie'.type:'getData'
},{ 
   title:'Bar chart'.type:'avgBqzs'}... ] For example: changeSelect(item:any){} @ts-ignore this[item.type]()}Copy the code

Vi. Individual project specifications

1. Try not to use for to make your code more enjoyable

ForEach traversal, Map conversion, filter filtering

2. Call the interface with async and await as much as possible

Such as:

private async getData() {   
   const { data } = await getTransactions({})
}Copy the code

3. Use deconstruction to get values when only partial filtering is required

public sizeTop={
  id:' ',
  City:' ',
  County:' ',
  time:' '
}

const {City,County}=this.sizeTop

 private async getData() {    
    const { data } = await getTransactions({City,County})
 }
Copy the code


The way ahead is so long without ending, yet high and low I’ll search with my will unbending.

Hope to be a big shot soon