preface

Programmers have a motto called “Don’t repeat Yourself” (DRY).

In the development, in order to realize the code reuse, reduce redundancy. Use common JS utility class methods, common styles, and encapsulate common components.

In addition, there are more commonly used mixin functions.

CSS preloads processor mixins

Using CSS preloading processors, such as SCSS, can be blended in by defining variables and styles.

The sample

Define variable variable. SCSS file

$blue: #409EFF;
$shadowBg: #f8f8f8;
Copy the code

Style mixed into mixin.scss file

@mixin clearfix {
  &:after {
    content: "";
    display: table;
    clear: both; }}@mixin border-shadow{
  border-radius: 4px;
  border: 1px solid #ebeef5;
  -webkit-box-shadow: 0 2px 12px 0 rgba(0.0.0.1);
  box-shadow: 0 2px 12px 0 rgba(0.0.0.1);
}
​
@mixin flex{
  display: flex;
  justify-content: center;
  align-items: center;
}
Copy the code

These common styles are then introduced into the VUE component to enable code reuse

<template>
  <div>
    <div class="select-role-wrapper">
      <div class="base">
      </div>   
    </div>
  </div>
</template>
<style lang="scss" scoped>
  @import "@/assets/scss/mixin.scss";
  @import "@/assets/scss/variable.scss";
  .base {
    @include border-shadow;
    .title {
      @include flex;
      height: 100px;
      background: $blue;
      justify-content: flex-start;
      text-align: left;
      padding: 0 20px;
      border-radius: 4px 4px 0 0;
      font-size: 18px; }}</style>
Copy the code

The Vue mixins

The Vue website, in the section on reusability & composition, also mentions mixins

basis

Mixins provide a very flexible way to distribute reusable functionality in Vue components.

A mixin object can contain any component option. When a component uses a mixin object, all the options for the mixin object are “mixed” into the component’s own options.

Option to merge

When components and mixins have options with the same name, these options are “merged” in the appropriate manner.

For example, data objects are recursively merged internally, and component data takes precedence in the event of a conflict.

The hook functions of the same name will be merged into an array and therefore both will be called. In addition, hooks mixed in with the object are called before the component’s own hooks.

In addition to public data, template layouts can also be mixed in. However, the template layout in mixins is replaced if you already have a template.

When the page logic is the same, you can introduce mixins with a lot less writing. No, you can introduce mixins according to your project requirements.

Please see the official document for details

Vue’s documentation is a delight to look at.

Cn.vuejs.org/v2/guide/mi…

Take a real project as an example:

Some common methods of requesting interfaces, and file-stream downloading methods, click events, can be put into mixins files

OperateMixin. Js file

import { parseTime } from "@/utils/common";
import { deleteColor } from "@/utils/common";
export const OperateMixin = {
  data() {
    return {
      deleteColor,
    }
  },
  created(){},methods: {
    // Click the operation button method
    btnClick(item) {
      let length = this.table.selection.length;
      let msg = "";
      if (length == 0 && item.alert) {
        msg = item.alert;
      }
      if (msg) {
        this.$sweetAlert.warnWithTimer(msg);
        return;
      }
      let ids = this.table.selection.map((item) = > item.ID).join(",");
      this.operate(ids, item.value);
    },
    operateBeforeConfirm(ids, type, msg, callback) {
      this.$confirm(msg, "Operation Tips", {
        confirmButtonText: "Sure".cancelButtonText: "Cancel".type: "warning",
      })
        .then(() = > {
          callback(ids, type);
        })
        .catch(() = >{}); },interfaceRequest(httpurl, formData, method, callback) {
      this.$api.httpAction(httpurl, formData, method).then((res) = > {
        if (res.code == 200) {
          this.$sweetAlert.successWithTimer(res.msg);
          callback();
        } else {
          this.$sweetAlert.errorWithTimer(res.msg); }}); },downloadByFileStream(httpurl, formData, name, format) {
      let fileName = name || parseTime(new Date(), "{y}-{m}-{d}");
      let formatName = format || 'zip';
      formatName = '. ' + formatName;
      this.$api.downFile(httpurl, formData).then((data) = > {
        if(! data) {this.$sweetAlert.errorWithTimer("File download failed!");
          return;
        }
        if (typeof window.navigator.msSaveBlob ! = ="undefined") {
          window.navigator.msSaveBlob(new Blob([data]), fileName + formatName);
        } else {
          const url = window.URL.createObjectURL(new Blob([data]));
          const link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", fileName + formatName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url); }}); }}}Copy the code

Then introduce it in the component

<template>
  <div class="wrapper">InfoList</div>
</template>
​
<script>
import { OperateMixin } from "@/mixins/OperateMixin";
export default {
  name: "InfoList".mixins: [OperateMixin],
  components: {},
  props: {},
  data() {
    return {};
  },
  watch: {},
  computed: {},
  methods: {},
  created() {},
  mounted(){}}; </script><style scoped>
.wrapper {
}
</style>
Copy the code