Mixins alternative to vue3.0 combined API

Mixins alternative to vue3.0 combined API

An alternative to mixins for the vue3.0 combined API - Brief Book

The traditional Vue2.0 mixin has the following shortcomings:

  1. Duplication of attribute names conflicts, which causes the data in the mixin to be replaced, sometimes causing unpredictable problems.
  2. Reusability is limited. No parameters can be passed to mixins to change the logic, which reduces the flexibility in abstract logic.
  3. The source of the data cannot be determined. The data in mixins is not explicitly listed, resulting in the source of many data or methods in the code being unable to be determined, and sometimes even causing the code to be accidentally deleted.

In vue3.0 we usecustom hooks to solve these problems

Display of traditional mixins:

export default {
  data () {
    return {
      msg: 1
    }
  },

  mounted () {
    this.testFn()
  },

  methods: {
    testFn () {
      console.log('testFn')
    }
  }
}

Use mixins:

<template>
  <div>{
   
   { aa }}</div>
</template>

<script>
import myMixins from './myMixins'
export default{
  mixins: [myMixins],
  mounted () {
    console.log('index mounted')
  }
}
</script>

How we use custom hooks:

import { ref, onMounted } from 'vue'

export default function () {
  const aa = ref(1)

  function testFn () {
    console.log('testFn')
  }

  onMounted(() => {
    testFn()
  })

  return {
    aa
  }
}
<template>
  <div>{
   
   { aa }}</div>
</template>

<script lang="ts">
import { defineComponent, onMounted } from 'vue'
import myHooks from './myHooks'

export default defineComponent({
  setup () {
    const { aa, testFn } = myHooks()

    onMounted(() => {
      testFn('index mounted')
    })

    return {
      aa,
      testFn
    }
  }
})
</script>

You can see that the data and methods I introduced using custom hooks can directly see the source, and the methods can pass in parameters.

Why is a function exported instead of an object?

  1. Because exporting as an object means that the encapsulated logic is executed when importing, and the logic we encapsulate is special code wrapped with the composition api. These codes can only be used normally in setup, so you need to export one function, so that the function can be called in the component setup to specify the execution time.
  2. Another purpose of exporting as function is to facilitate parameter passing, so that some differentiated logic processing can be done when different components are referenced.

 

Guess you like

Origin blog.csdn.net/wwf1225/article/details/129875693