A little known high performance component registration and implementation of component sorting skills

Time:2020-10-31

A little known high performance component registration and implementation of component sorting skills

background

On the way to Vue, you must know how to register and call a component

We usually use three steps to implement the whole process of calling components

  • adoptimportIntroducing components
  • The component object in the parent componentcomponentsRegister imported subcomponents
  • Use the component in the parent component
<template>
  <div>
    <Child msg="Hello World!"/>
  </div>
</template>

<script>
import Child from "../components/Child";

export default {
  name: "page",
  components: {
    Child
  }
};
</script>

This is probably the most common mode of using sub components by 80% Vue friends. Yes, I often do this too… If you are tired of using this method and want to change to a new one, we will learn two rarely used but highly efficient use methods to improve the development force.

Preset Scene 1

Imagine a member center component. There are some areas for showing the differences between members and members. But these two will only show one of them, members and non members. Suppose we have it nowMemberInfoas well asUserInfoTwo components, we want to display the corresponding module according to the user identity

Implementation scheme 1

This is probably the way most front-end players will think of, including myself, often (covering my face)

<template>
  <div class="container">
    < button @ Click = "ismember =! Ismember" > {ismember? 'I don't want to be a member, hum':'I want to be a member '}} >
    <UserInfo v-if="!isMember"/>
    <MemberInfo v-else/>
  </div>
</template>

<script>
import UserInfo from "../components/UserInfo";
import MemberInfo from "../components/MemberInfo";

export default {
  name: "user",
  data() {
    return {
      isMember: false
    };
  },
  components: {
    UserInfo,
    MemberInfo
  }
};
</script>

A little known high performance component registration and implementation of component sorting skills

Implementation scheme 2

By reading the official documents, we will find that Vue has provided a built-in component, rendering a “meta component” as a dynamic component. According to < span style=“ color:red >is< / span > to determine which component is rendered. If you don’t know this, we will send it to the official website at the end of the article

<template>
  <div class="container">
    < button @ Click = "ismember =! Ismember" > {ismember? 'I don't want to be a member, hum':'I want to be a member '}} >
    <component :is="userComponentName"/>
  </div>
</template>

<script>
import UserInfo from "../components/UserInfo";
import MemberInfo from "../components/MemberInfo";

export default {
  name: "userComponent",
  data() {
    return {
      isMember: false
    };
  },
  components: {
    UserInfo,
    MemberInfo
  },
  computed: {
    userComponentName() {
      let { isMember } = this;
      return isMember ? "member-info" : "user-info";
    }
  }
};
</script>

A little known high performance component registration and implementation of component sorting skills

From scenario 1 to scenario 2, it is obvious that we work with built-in components by calculating propertiescomponentPerfectly eliminatedv-if/v-elseThe logical judgment of can also do data transmission normally

It’s just that from now on, there’s no difference except that the usage method has changed. This is not what I want to introduce this time. For the existing two module components, we still have to import and register to complete the call. Now, we don’t want to register the required sub components in advance, because it’s too cumbersome and wastes performance. We want to try to import and register dynamically. Let’s move on and rush!

Implementation scheme 3

<template>
  <div class="container">
    < button @ Click = "ismember =! Ismember" > {ismember? 'I don't want to be a member, hum':'I want to be a member '}} >
    <component :is="userComponentImstance"/>
  </div>
</template>

<script>
export default {
  name: "userImport",
  data() {
    return {
      isMember: false
    };
  },
  computed: {
    userComponentImstance() {
      let { isMember } = this;
      let pathName = isMember ? "MemberInfo" : "UserInfo";
      //Component separation is realized by importing components dynamically with webpack
      return () => import(`../components/${pathName}`);
    }
  }
};
</script>

As you can see, we are no longer calling in the form of importing registration components in advance,componentDirectly provide it with a complete component object
By reading the official documentation, we can see that is receives one of two options:

  • Registered component name
  • Component object

Now, let’s go through the dynamicimportThe sub components are imported in the form ofcomputedRender the corresponding sub components according to the conditions, and who uses them will know. Only when the program is running, we can save the form of importing and registering components in advance. Does this effect have a familiar flavor with on-demand loading when using third-party components.. well, yes, it has the same effect as router lazy loading when optimizing spa performance.

When we changeisMemberThis variable can be used to switch components dynamically. The advantage of this is that when we use dynamic import,webpackA separate file is created for each file that matches the import functionchunkIn other words, we often call it subcontracting loading, instead of loading all components at once. The current sample can not see how much performance improvement, but in actual development, this advantage will be very obvious.

If you knowwebpackYou can make good use of this to split the code and DIY is a loading strategy of your own program. It can be done throughLearn about code splitting

Scene preset 2

I met a requirement before, that is to render several activity modules of the mall home page in turn according to the back-end return order. At that time, I didn’t want to understand how to implement it. And now, when you see this, I think you have a little bit of a thought. If not, it must be my fault. The article is not clear enough. Now you know the built-in componentscomponentAs well as our dynamic loading, we can easily implement it.

Assuming that our parent component is the home page, it may existSeckillSecond killGroupGroup buyingLimitPurchase restrictionBargainBargaining four activity modules, module display and ranking are determined by the data, not by ushard coded

<template>
  <div>
    <p>Pretend this is the front page of a mall</p>
    < button @ Click = "shuffle" > random switching module sequence
    <component :is="item.imstance" v-for="(item ,i) in componentImstances" :info="item" :key="i"/>
  </div>
</template>

<script>
export default {
  name: "home",
  data() {
    return {
      moduleList: [
        {
          type: "Bargain",
          Title: "bargaining",
          startTime: "2019-12-01",
          endTime: "2019-01-01"
        },
        {
          type: "Seckill",

          Title: "seckill",
          startTime: "2019-12-05",
          endTime: "2019-01-01"
        },
        {
          type: "Limit",

          Title: "purchase restriction",
          startTime: "2019-12-07",
          endTime: "2019-01-01"
        },
        {
          type: "Group",
          Title: "group buying",
          startTime: "2019-12-11",
          endTime: "2019-01-01"
        }
      ]
    };
  },
  components: {},
  methods: {
    shuffle() {
      let { moduleList } = this;
      let resultArr = [];
      while (moduleList.length > 0) {
        var index = Math.floor(Math.random() * moduleList.length);
        resultArr.push(moduleList[index]);
        moduleList.splice(index, 1);
      }
      this.moduleList = resultArr;
    }
  },
  computed: {
    componentImstances() {
      let { moduleList } = this;
      return moduleList.map(item => {
        item.imstance = () => import(`../components/${item.type}`);
        return item;
      });
    }
  }
};
</script>

A little known high performance component registration and implementation of component sorting skills

In this way, we can realize the user-defined sorting of our active modules. However, at present, our module dynamic import is loaded according to the data returned from the back-end. No one will know whether there will be any problems in the middle. In order to avoid loading failure of dynamically imported components under unknown circumstances, we can make an exception template prompt.
Put thecomponentImstancesSlightly modified:

computed: {
    componentImstances() {
      let { moduleList } = this;
      return moduleList.map(item => {
        item.imstance = () => {
          return new Promise((resove, reject) => {
            let imstance = import(`../components/${item.type}`);
            imstance.then(res => {
              resove(res);
            });
            imstance.catch(e => {
              resove(import("../components/Error"));
            });
          });
        };
        return item;
      });
    }
  }

A little known high performance component registration and implementation of component sorting skills
We will dynamically import abnormal components, capture and output the default template. User experience must be your long cherished wish

reference resources:

Vue built in components

webpack

summary

Flexible use of component and import. If a component has many different attempts, it is very useful and easy to expand. Because it is asynchronous, templates are loaded only when needed, making the code lighter. As a digression, component can cache components with keep alive, and the effect is also excellent. Oh, this article will not repeat it. Relevant demo source code has been updated to GitHub portal.

❤️ last

If you think this article is enlightening to you:

Share it so that more people can see it (welcomegive the thumbs-upandfollow😊)

Pay attention to the official account “Front end dried shrimps“, share front-end dry goods weekly

A little known high performance component registration and implementation of component sorting skills

Recommended Today

CKB developers share exclusive secrets with live coding for the first time

Yesterday, the elder sister carried out the first live coding for three hours in the nervos live studio. During the live broadcast, she realized the open transaction live, and responded to everyone’s request, and the women’s clothing appeared on the screen. 👇👇👇 If the response is good, we will continue to make a series of […]