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


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[] ? '' : hash[] = 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


export default {
  name: 'App',
  components: {
  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

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

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

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, location).catch(error => error)

const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (to) {
  return, 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


//Add a timestamp when the route jumps

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

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


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.

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 =
    if (now - start >= wait){
    // Point this to the event source object, e)
      start = now

Use throttling

    window.addEventListener('scroll', throttle(function(e){
    }, 500))

Anti shake function encapsulation

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

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

   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

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

12. Package axios

axios package

13. Use of keepalive

14.grid layout

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

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

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

20. Difference between cookie and session

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


    This hook. Execution effect dependence



    • 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: "/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) {
      path: '/login'
  } else {
    if (to.path == '/login' && token) {
    } else {     

Topics: Javascript Vue.js