Front end knowledge points

Posted by kendall on Thu, 17 Feb 2022 09:02:22 +0100

1. De duplication of the same object in the array

The reduce() method receives a function as an accumulator. Each value in the array is reduced from left to right and finally calculated as a value

Syntax:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
let arr = [{id:1},{id:2},{id:3},{id:1}]
const hash = {}
arr = arr.reduce((item, next) => { hash[next.id] ? '' : hash[next.id] = true && item.push(next)
 return item
}, [])

2. Put public methods into mixins

Extract public methods or data from mixins files

Introduce mixins into components that need to use public methods: [mixins]

3. Refresh the page and get the list again after adding, deleting, modifying and querying

Using provide and inject

Function: it can be used to transfer data from parent component to descendant component. It is mainly used to refresh vue component

How to use: provide returns the data to be passed to the lower level in the parent component, and inject data into the child component or grandchildren and other lower level components that need to use this data

On app In Vue

<template>
  <div
    id="app"
  >
    <router-view
      v-if="isRouterAlive"
    />
  </div>
</template>

<script>
export default {
  name: 'App',
  components: {
    MergeTipDialog,
    BreakNetTip
  },
  data () {
    return {
      isShow: false,
      isRouterAlive: true
  },

// The parent component returns the data to be passed to the child
  provide () {
    return {
      reload: this.reload
    }
  },
  methods: {
    reload () {
      this.isRouterAlive = false
      this.$nextTick(() => {
        this.isRouterAlive = true
      })
    }
  }
}
</script>

It is introduced in the subcomponent that needs to refresh the component

//Reference vue reload method
inject: ['reload'],
methods: {
    async xxx () {
        this.reload()
    }
}

4. Navigation hook in Vue router

5.vuex modularization

6. Solve the problem that vue routes jump to the same address, that is, repeat the current route and report errors under the current route

const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(error => error)
}

const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (to) {
  return VueRouterReplace.call(this, to).catch(err => err)
}

7. When vue jumps to the same route - refresh this route

When you repeatedly click the same navigation and jump to the same route, you will only jump once, and repeated clicks will not refresh

resolvent:

//Add a timestamp when the route jumps
this.$router.push({
    name:"...",
    query:{
        t: Date.now(),
    },
})

Then add the key attribute to the router view, and the value is the timestamp:

<router-view :key="$route.query.t" />

8.nextTick

nextTick() is called after the callback function is delayed after the next dom update data. The simple understanding is that when the data is updated and rendered in dom, the function is automatically executed.

https://www.jianshu.com/p/a7550c0e164f

9. Throttling and anti shake

Throttle function encapsulation

// The throttling of the function is suitable for multiple times of time, which is evenly distributed and triggered according to time
// Usage scenario: window adjustment, page scrolling, drag and drop function, rush purchase, crazy Click
function throttle(callback, wait) {
  let start = 0;
  // Returns a function
  return function(e) {
    let now = Date.now()
    if (now - start >= wait){
    // Point this to the event source object
      callback.call(this, e)
      start = now
    }
  }
}

Use throttling

 <script>
    window.addEventListener('scroll', throttle(function(e){
      console.log(Date.now())
    }, 500))
  </script>

Anti shake function encapsulation

// Usage scenario: form input
// Function anti shake
function debounce(callback, wait) {
  let timeId = null;
  return function(e) {
    if(timeId !== null) {
      clearInterval(timeId)
    }
    timeId = setTimeout(()=> {
      callback.call(this, e)
      // Reset timer variable
      timeId = null
    }, wait)
  }
}
<script>
    let input = document.querySelector('input')
    input.onkeydown = debounce(function(e) {
        console.log(e.keyCode);
    },1000)
 </script>

10. If you want to modify the vant style and use / deep / under sass loader, use:: v-deep instead

.type-4{
   width: 100%;
  	 ::v-deep img{
    	width: 100% !important;
  	 }
  }

11. Use the computed calculation attribute to transfer parameters

According to the requirements, recalculate the width and height according to the transmitted aspect ratio

computed:{
    imgWD(o){
      return function(o){
        return {
            width:'370px',
            height:370*(1/o) + 'px'
        }
      }
    }
  }
<div :style="imgWD(item.crown)" class="img-detail">
  <image resize='stretch' class="itemPhoto" 		:src="imgUrl + item.photoName"></image>
</div>

12. Package axios

axios package

13. Use of keepalive

https://www.cnblogs.com/mary-123/p/11248178.html

14.grid layout

https://wudi98.blog.csdn.net/article/details/93379228?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.control&dist_request_id=c8b220c5-016f-461e-ab43-f264a6e7207b&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-4.control

15. Wechat applet cloud development stepping point

When you want to modify the status of data in the database, you can't use the database's native update method to modify successfully, which will lead to zero update status in stas and failure of modification. You must use cloud functions to modify the status, such as the change of collection and praise status

16. Thoughts on "asynchronously loading css" and its implementation

https://blog.csdn.net/weixin_38129930/article/details/101444305

17.['1', '2', '3'].map(parseInt)

The output is [1,NaN,NaN]

//Note: the difference between Number() and parseInt()

18. Analysis of the difference between defer and async

https://segmentfault.com/a/1190000017257370?utm_source=tag-newest

19. Cross domain issues

Reason: the same origin strategy of the browser leads to cross domain. When the protocol, domain name and port number of the requesting interface are different from the requested protocol, domain name and port number, cross domain problems will occur

https://segmentfault.com/a/1190000015597029

20. Difference between cookie and session

https://www.cnblogs.com/l199616j/p/11195667.html

21. Dead cycle caused by Vue global pre guard and Its Solutions

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // ...
}
)

When a navigation is triggered, the global front guard is called according to the creation order. The guard is executed asynchronously. At this time, the navigation is waiting until all guards resolve.

Each guard method receives three parameters:

  • to: Route: the target to enter Routing object

  • from: Route: the route that the current navigation is about to leave

  • next: Function Be sure to call this method to

    resolve

    This hook. Execution effect dependence

    next
    

    Method.

    • next(): the next hook in the pipeline. If all hooks are executed, the status of navigation is confirmed.
    • next(false): interrupt the current navigation. If the URL of the browser is changed (it may be the user's manual or the browser Back button), the URL address will be reset to the address corresponding to the from route.
    • next('/') or next({path: '/'}): jump to a different address. The current navigation is interrupted and a new navigation is performed. You can pass any location object to next, and you are allowed to set options such as replace: true, name: 'home' and any Route link to prop or router.push Options in.
    • next(error): (2.4.0 +) if the parameter passed into next is an Error instance, the navigation will be terminated and the Error will be passed to router.onError() Registered callback.

Make sure to call the next method, otherwise the hook will not be resolved

Error method:

If sessionStorage has a token, and if the target path to enter is the login page, jump to the / dashboard page. If it is other pages, enter

If sessionStorage does not have a token, enter the login page

This will cause an endless loop, because each time the path changes, the front navigation guard will be executed again

router.beforeEach((to,from,next) =>{
  if (sessionStorage.getItem("token")) {
     if(to.path === "/login"){
       next({path:"/dashboard"})
     }
     else{
       alert("1")
       next()
     }     
  }else{
    next({path: "/login"})   // The front navigation guard will be executed again because the path changes
  }
})
Correct method:
router.beforeEach((to, from, next) => {
  let token = window.sessionStorage.getItem('token');
  if (to.path != '/login' && !token) {
    next({
      path: '/login'
    })
  } else {
    if (to.path == '/login' && token) {
      next('/dashboard')
    } else {     
      next()
    }
  }
})

Topics: Javascript Vue.js