Some tips in vue combat

Lazy loading of routes that can make you load faster for the first time, how can you forget?

Routing lazy loading allows our package to load only the routing components of the current page without loading all the pages at once.

For example 🌰, if it is written 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
    }
  ]
})
copy

Therefore, the above writing method should be avoided, and lazy loading should be used as much as possible.

Lazy loading writing method, combined with webpack import

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')
    }
  ]
})
copy

Do you remember there was a method called Object.freeze?

All students should know that when vue is initialized, the data in the data will be turned 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 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.

🌰

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

Asynchronous components are so strong, 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.

🌰

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

The package loaded for the first time does not contain the modified component code

When a click triggers a certain behavior the introduced package looks like this

There is also a more complete way of writing asynchronous components

🌰

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

Are you still using this in computed?

I guess there are many students who use this.xxx in the computed property to get the data in the data, and the methods in the methods, and maybe get the state of vuex, and commit, etc. through this.$store, and even, still The data in the route will be obtained through this.$route. Actually, we can avoid these ugly this, and it can even give us unseen performance problems. In terms of implementation, the data we can access through this can be structured on the first parameter of computed.

🌰

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

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

Why avoid using both v-if and v-for on the same element? Because there is a piece of code in vue's source code to deal with the priority of instructions, this 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, and in some cases, they don't need to be displayed. When vue still loops this 100 The data shows, and then to judge v-if, therefore, we should avoid this situation.

bad 🌰

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

ok 🌰

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

So why don't you use the strong .sync modifier?

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

🌰

 // 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>
copy

$attr and $listeners let you encapsulate components like a duck!

$attr and $listeners may not be used by many students. In fact, they allow us to re-encapsulate the components of some component libraries, which are very easy to use.

Briefly describe the two of them:

$attr: If a component not only passes the properties required by prop, but also other properties other than prop, then these properties will be collected in $attr.

$listeners: If a component passes a custom event, but the child component does not fire through emit, then these custom methods will be collected in $listeners.

Here is a simple secondary encapsulation of the Tabel component of ElementUI 🌰

Refer to the vue actual combat video explanation: into learning

<el-table    v-bind="$attrs"
   v-on="$listeners">
   <template v-for="item in column">
    <el-table-column v-bind="item" />
   </template>
</el-table>
<script>
export default {  props:{      column:{        type:Array,        required:true
      }   }}<script>
copy

v-model also has such a nice modifier!

There are 3 easy-to-use modifiers on v-model, I don't know if you have used them, one is lazy, one is number, and one is trim.

lazy: can turn @input events into @blur events

number: Only numeric values ​​can be entered

trim: clear the spaces on both sides

🌰

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

Did you know that v-model can also customize properties?

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

🌰

// 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>
copy

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?

🌰

// 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>
copy

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

Sometimes we are operating the scrolling behavior of the page, then we will think of scrollTop for the first time. In fact, we have a second choice, which is the scrollBehavior hook provided by VueRouter.

🌰

const router = new VueRouter({
  routes:[...] ,
  scrollBehavior(to,from,position){
      // The position parameter can print Kangkang by itself, click the left and right arrows of the browser to trigger
      return{
          // There are many parameters that can be returned here, just a few are listed below. For details, please refer to the official website of Kangkang
          x:100,
          y:100,
          selector:#app,
          offset:200,
          //and many more
      }
  }
})
copy

The native event you define on the child component does not take effect?

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

🌰

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

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

🌰

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

Use keep-alive to cache your page status!

keep-alive can help us keep the previous component from being destroyed when switching components. It is more commonly used in the management background system.

🌰

<keep-alive>
    <router-view></router-view>
</keep-alive>
copy

Tags: Vue Vue.js JQuery

Posted by Jtech inc. on Mon, 17 Oct 2022 16:18:08 +1030