Vue combat [commonly used Vue magic]

🌟Foreword

Hello everyone, in the last issue, I summarized some common Vue errors and how to solve them, and I also received a lot of supplements from my friends in private; the friends are really too strong, and it is really great to learn and progress together with you happy. Today, the blogger will summarize for you some small Vue magics that are often used in actual combat, which can greatly improve your development and project performance. Let's take a look together.

🌟Lazy loading of routes that can make your first load faster, how can you forget?

Routing lazy loading can make our package not need to load all pages at once, but only load the routing components of the current page.

For example, if you write it like this, it will all be loaded when loading.

const router = new VueRouter({
  routes:[
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/about',
      name: 'About',
      component: About
    }
  ]
})

Therefore, the above writing method should be avoided, and lazy loading should be used as much as possible, combined with the import of webpack

const router = new VueRouter({
  routes:[
    {
      path: '/',
      name: 'Home',
      component: () => import(/* webpackChunkName: "home" */ '../views/Home.vue')
    },
    {
      path: '/about',
      name: 'About',
      component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
    }
  ]
})

🌟Do you still remember that there is a method called Object.freeze?

All students should know that when vue is initialized, all the data in data will be made into responsive data. However, when we write business logic, some data will never change once it is initialized. It does not need to be made into responsive data by vue at all, so we should freeze the data that does not need to be changed through the Object.freeze method. Avoid doing some useless operations when vue is initialized.

give a 🌰

export default {
  data:()=>({
    list:Object.freeze([{title:'I never need to change, I don't need responsive'}])
  })
}

🌟Asynchronous components are so powerful, have you never used them?

Asynchronous components allow us to load some components when we need them, instead of loading them as soon as they are initialized, which is a concept with lazy loading of routes.

give a 🌰

export default {
  components:{
    AsyncComponent:()=>import(/* webpackChunkName: "AsyncComponent" */ './Async')
  }
}

There is also a more complete way of writing asynchronous components

give a 🌰

export default {
  components:{
    AsyncComponent:()=>({
      component:import(/* webpackChunkName: "AsyncComponent" */ './Async'),
      delay:200, // Delay in milliseconds, default 200
      timeout:3000, // It times out after loading a few millimeters and triggers the error component
      loading:LoadingComponent, // Displayed before the component is not loaded back
      error:ErrorComponent // Displayed when the component times out
    })
  }
}

🌟Are you still using this in computed?

I guess there are still many students who use this.xxx to get the data in data and the methods in methods in the computed attribute, and maybe use this.route to get the data in the route. In fact, we can avoid these ugly this, it will even bring us invisible performance problems. In terms of implementation, the data we can access through this can be deconstructed on the first parameter of computed.

give a 🌰

export default {
   haha({$attrs,$route,$store,$listeners,$ref}){
     // It can also structure many attributes, and can print Kangkang by itself
     return 
   }
}

🌟How to avoid using v-if and v-for together?

Why avoid using v-if and v-for on the same element at the same time? Because there is a piece of code in the source code of vue that deals with the priority of instructions, this piece of code processes v-for first and then v-if. So if we use two instructions together in the same layer, there will be some unnecessary performance problems. For example, this list has a hundred pieces of data. In some cases, they don’t need to be displayed. When vue will still loop this 100 The data shows, and then judge the v-if, so we should avoid this situation.

bad 🌰

<h3 v-if="status" v-for="item in 100" :key="item">{{item}}</h3>

ok 🌰

<template v-if="status" >
    <h3 v-for="item in 100" :key="item">{{item}}</h3>
</template>

Why v-if and v-for are not recommended to be used together

Do not use v-for and v-if in the same tag, because v-for is parsed first and then v-if is parsed. If you need to use it at the same time, you can consider appealing or writing as a calculated attribute.

🌟Why don't you use such a strong .sync modifier?

If you want to control the display and hiding of a child component in the parent component, is it still passing a prop and a custom method, which will be troublesome, try the sync modifier.

give a 🌰

// parent component
 template>
  <div>
    <Toggle :show.sync = 'show'></Toggle>
  </div>
</template>

//Toggle Components

<template>
  <div>
    <div v-if="show">
    Show and hide components
  </div>
  <button @click="test">hidden components</button>
  </div>
</template>
<script>

export default {
  props:['show'],
  methods: {
    test(){
      this.$emit('update:show',false)
    }
  }
}
</script>

🌟v-model also has such nice modifiers!

There are 3 useful modifiers on v-model. I don’t know if you have used them. One is lazy, one is number, and the other is trim.

  • lazy: You can turn @input events into @blur events;
  • number: Only numeric values ​​can be entered;
  • trim: empty the spaces on both sides

give a 🌰

   //lazy
   <input v-model.lazy="msg" />
   //number
   <input v-model.number="msg" />
   //trim
   <input v-model.trim="msg" />

🌟Other modifiers

event modifier

  • .stop prevents the event from continuing to propagate;
  • .prevent prevents browser or tab default behavior;
  • .capture uses the event capture mode, that is, the event triggered by the element itself is processed here first, and then handed over to the internal element for processing;
  • .self triggers the handler only when event.target is the current element itself;
  • The .once event will only fire once;
  • .passive tells the browser that you don't want to prevent the event's default behavior.

Modifiers for keyboard events

  • .enter (capture "Enter" key)
  • .tab (captures the "indent" key)
  • .delete (captures "delete" and "backspace" keys)
  • .esc (captures the "escape" key)
  • .space (capture the "space" key)
  • .up (capture "up" key)
  • .down( capture "down" key)
  • .left (capture "left" key)
  • .right (capture "right" key)

mouse button modifier

  • .left
  • .right
  • .middle

🌟Do you know that v-model can also customize attributes?

If you want to use v-model on a custom Input component, you need to introduce a value in the subcomponent and trigger the input event. The default syntactic sugar of v-model is the combination of these two things.

give a 🌰

// parent component
<template>
  <div>
    <CustomInput v-model='msg' />
  </div>
</template>

//CustomInput

<template>
  <div>
    <input type="text" :value="value" @input="test">
  </div>
</template>
<script>
export default {
  props:['value'],
  methods: {
    test(e){
      this.$emit('input',e.target.value)
    }
  },
}
</script>

However, what if the component is not an input, but a checkbox or a radio? I don't want to receive a value and input event, I want to receive a more semantic checked and change event, what should I do?

give a 🌰

// The parent component does not need to be changed
...
//CustomInput
<template>
  <div>
    <input type="checkbox" :checked="checked" @change="test">
  </div>
</template>
<script>
 props:['checked'],
 model:{
    props:'checked',
    event:'change'
  },
  methods: {
    test(e){
      this.$emit('change',e.target.checked)
    }
  }
}
</script>

🌟Are you still scrolling your page with your browser's scrollTop?

Sometimes we are manipulating the scrolling behavior of the page, then we will immediately think of scrollTop. In fact, we still have a second option, which is the scrollBehavior hook provided by VueRouter.

give a 🌰

const router = new VueRouter({
  routes:[...] ,
  scrollBehavior(to,from,position){
      // The position parameter can print Kangkang by itself, and it will be triggered by clicking the left and right arrows of the browser
      return{
          // There are many parameters that can be returned here, and the following is a simple list of a few. For details, go to Kangkang official website
          x:100,
          y:100,
          selector:#app,
          offset:200,
          //etc.
      }
  }
})

🌟The native event you defined on the subcomponent doesn't take effect?

Sometimes we want to listen to some events on subcomponents, such as click, but no matter what you click, it doesn't respond, why?

give a 🌰

<template>
    <div>
        <Child @click="test"></Child>
    </div>
</template>
<script>
    methods:{
        test(){}
    }
</script>

Because writing vue like this will think that you have customized a click event, which needs to be triggered by $emit('click') in the subcomponent. What if I just want to trigger it in the parent component? Then use the native modifier.

give a 🌰

<template>
    <div>
        <Child @click.native="test"></Child>
    </div>
</template>
<script>
    methods:{
        test(){}
    }
</script>

🌟How to solve Vuex page refresh data loss

vuex data persistence needs to be done. Generally, a local storage solution is used to save data. You can design your own storage solution or use a third-party plug-in;
It is recommended to use the vuex-persist plugin, which is a plugin for Vuex persistent storage. You don't need to manually access storage, but directly save the state to cookie or localStorage

🌟Written at the end

This article analyzes some of the more common errors in vue development. Have you experienced them? In the future, we will continue to update some practical magic of Vue for our friends! Dear friends, let’s be prepared at all times!

🌟 Write functions in the JSON package, follow bloggers and don't get lost

✨It's not easy to be original, and I hope you guys will support me!
👍 Like, your recognition is the driving force for my creation!
⭐️ Favorite, your favor is the direction of my efforts!
✏️ Comment, your opinion is the wealth of my progress!

Tags: Javascript Vue.js Vue Front-end

Posted by dolce on Wed, 22 Mar 2023 23:08:54 +0530