Vue combat of enterprise development [FAQ]

1.vue framework Precautions and experience

Vue 1.1 solve dynamic routing parameters, page data is not updated

Problem Description:

The dynamic routing encountered: / page /: id from / page / 1 switching to / page / 2 is not updated page components found

1 solution: give A distinct increase: key value, so that it will recognize vue This is different from the.

<router-view :key="key"></router-view>
  ...
  computed:{
        key(){
            return this.$route.path + Math.random();
        }
    }

Solution 2: Use the new v2.2 within the component beforeRouteUpdate

beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },

1.2 vue components in the destruction of timer **

Problem Description:

In a page to write a timer, once per second print, and then jump to b page, then you can see, the timer is still running. Recommended solution: the position after you have defined a timer to clear the timer by $ once this event listener is.

const timer = setInterval(() => {
    // 定时器操作
}, 1000)
// 通过$once来监听定时器,在beforeDestroy钩子可以被清除。
this.$once('hook:beforeDestroy', () => {            
    clearInterval(timer);                                    
})

You can also use life-cycle statement:

export default {
    beforeDestroy(){
        clearInterval(timer);
    }
}

1.3 vue-demand loading assembly of two ways **

1. resolve => require ([ './ ComponentA'], resolve), as follows:

const ComponentA = resolve => require(['./ComponentA'], resolve)

Using 2 () => import (), the specific code is as follows:

const ComponentA = () => import('./ComponentA')

1.4 between the components, a communication scheme between components Sons

Communication scheme between components:

  • By event bus (bus), that is, by posting subscribe
  • vuex
  • Sons components:
    • Parent components pass data to self-assembly by prop
  • Sub-component binding custom events,. $ Emit (event, params) to invoke a custom event through this
  • Use vue provided $ parent / $ children & $ refs communication method
  • provide/inject
  • Communication between $ attrs deep-seated components, $ listeners

In 1.5 vue $ event usage - get the current parent element, child elements, siblings

<button @click = “fun($event)”>点击</button>
  ...
  
  methods: {
   fun(e) {
    // e.target 是你当前点击的元素
    // e.currentTarget 是你绑定事件的元素
    #获得点击元素的前一个元素
    e.currentTarget.previousElementSibling.innerHTML
    #获得点击元素的第一个子元素
    e.currentTarget.firstElementChild
    # 获得点击元素的下一个元素
    e.currentTarget.nextElementSibling
    # 获得点击元素中id为string的元素
    e.currentTarget.getElementById("string")
    # 获得点击元素的string属性
    e.currentTarget.getAttributeNode('string')
    # 获得点击元素的父级元素
    e.currentTarget.parentElement
    # 获得点击元素的前一个元素的第一个子元素的HTML值
  e.currentTarget.previousElementSibling.firstElementChild.innerHTML
  
    }
        }

1.6 axios second package http request

import axios from 'axios'
import router from '@/router'
import {removeSessionStorage} from './storage';
import Vue from 'vue'
import { Message } from 'element-ui' // 引用element-ui的加载和消息提示组件
// 请求超时时间配置
axios.defaults.timeout = 30000;
// api地址配置
axios.defaults.baseURL = "";
// console.log(process.env.VUE_APP_BASE_API)
Vue.prototype.$http = axios
// 在全局请求和响应拦截器中添加请求状态
let loading = null

// 请求拦截器
axios.interceptors.request.use(
    config => {
      config.headers = {
        'Content-Type': 'application/json'
      };
      // loading = Loading.service({ text: '拼命加载中' })
      let token = sessionStorage.getItem('-_token_-');
      if (token) {
        config.headers['token'] = token;
      }
      return config
    },
    error => {
      return Promise.reject(error)
    }
)

// 响应拦截器
axios.interceptors.response.use(
    response => {
      if (loading) {
        loading.close()
      }
        // 自定义错误码,各公司根据约定都不一样
        // 此处省略业务处理代码
        let errorCode = response.data.errCode;
        if(errorCode==='000000'){
          return Promise.resolve(response.data);
        }else {
            router.push({
              name: 'error',
              params: {
                isTimeout: false,
                path: router.currentRoute.path,
                desc: '您请求的资源找不到(错误码:404) ',
              },
            });
        } 
    },
    error => {
      if (loading) {
        loading.close();
      }
        // 此处省略业务处理代码
      return Promise.reject(error);
    }
);

1.7 development environment proxy switching configurations

To deal with such cross-domain scenario, during code development, devServer to a local agent to the back end, when tested, but also to modify the agent to the test environment, on the line, commissioning new problem may be to online environment agency

The code operating environment for node.js, use process.env can get into the system environment variables to distinguish the current machine is the company's production machinery, or personal development machine

To be vue.config.js configuration

const Timestamp = new Date().getTime();  //当前时间为了防止打包缓存不刷新,所以给每个js文件都加一个时间戳
const proxyTargetMap = {
    prod: 'https://xxx.xxx.com/',
    dev: 'http://192.168.200.230:6379',
    test: 'http://test.xxx.com',
    local: 'http://localhost:8080/'
}
let proxyTarget = proxyTargetMap[process.env.API_TYPE] || proxyTargetMap.local
module.exports = {
    publicPath: process.env.NODE_ENV === 'production' ? '/' : '/',
    outputDir: 'dist',
    assetsDir: 'static',
    lintOnSave: false, // 是否开启eslint保存检测
    productionSourceMap: false, // 是否在构建生产包时生成sourcdeMap
    // 调整内部的 webpack 配置。
    // 查阅 https://github.com/vuejs/vue-docs-zh-cn/blob/master/vue-cli/webpack.md
    chainWebpack: () => { },
    //configureWebpack 这部分打包文件添加时间戳,防止缓存不更新
    configureWebpack: {
        output: { // 输出重构  打包编译后的 文件名称  【模块名称.版本号.时间戳】
            filename: `[name].${process.env.VUE_APP_Version}.${Timestamp}.js`,
            chunkFilename: `[name].${process.env.VUE_APP_Version}.${Timestamp}.js`
        },
    },

    devServer : {
        proxy: {
            '/api' : {
                target: proxyTarget,
                changeOrigin: true,
                pathRewrite: {
                    '^/api' : ''
                }
            }
        }
    }
};

Corresponding to the configuration package.json

See the following cross-env API_TYPE = dev

cross-env is a global command-line tool that can change the current environment variables based on different platforms, enabling developers can be on the machine, selective call development mode or production mode

"scripts": {
  "serve": "vue-cli-service serve --mode development",
+  "serve:dev": "cross-env API_TYPE=dev vue-cli-service serve --mode development",
+  "serve:test": "cross-env API_TYPE=test vue-cli-service serve --mode development",
  "build": "vue-cli-service build --mode production",
  "test": "vue-cli-service build --mode test",
  },

image

Published 35 original articles · won praise 64 · views 10000 +

Guess you like

Origin blog.csdn.net/tjx11111/article/details/104429832