组合式API重用对于mixin的优势

603 阅读1分钟

mixin: 缺点,从mixin获取到的变量,方法不知道由哪个mixin注入的,也可能有命名冲突问题

slot: 缺点新建了组件实例,有不必要的性能开销

组合式api: 明确注入变量, 解决了命名冲突问题

实例代码

mixin方式

<div id="app"></div>
<script>
  const { createApp } = Vue

  const Mousemixin = {
    data() {
      return { x: 0, y: 0 }
    },
    methods: {
      update(e) {
        this.x = e.pageX
        this.y = e.pageY
      },
    },
    mounted() {
      window.addEventListener('mousemove', this.update)
    },
    unmounted() {
      window.removeEventListener('mousemove', this.update)
    },
  }
  const App = {
    mixins: [Mousemixin],
    tempate: '{{x}}{{y}}',
  }

  createApp(App).mount('#app')
</script>

slot方式

<div id="app"></div>
<script>
  const { createApp } = Vue

  const Mouse = {
    render() {
      return (
        this.$slots.default &&
        this.$slots.default({
          x: this.x,
          y: this.y,
        })
      )
      // the same as <slot :x='x' :y='y'></slot>
    },
    data() {
      return { x: 0, y: 0 }
    },
    methods: {
      update(e) {
        this.x = e.pageX
        this.y = e.pageY
      },
    },
    mounted() {
      window.addEventListener('mousemove', this.update)
    },
    unmounted() {
      window.removeEventListener('mousemove', this.update)
    },
  }
  const App = {
    componentes: { Mouse },
    tempate: `<Mouse v-slot="{x, y}">{{x}}{{y}}</Mouse>`,
  }

  createApp(App).mount('#app')
</script>

组合式api方式

<div id="app"></div>
<script>
  const { createApp, h, ref, onMounted, onUnmounted } = Vue

  function userMouse() {
    const x = ref(0)
    const y = ref(0)

    const update = (e) => {
      x.value = e.pageX
      y.value = e.pageY
    }

    onMounted(() => {
      window.addEventListener('mousemove', update)
    })

    onUnmounted(() => {
      window.removeEventListener('mousemove', update)
    })

    return {
      x,
      y,
    }
  }

  const App = {
    setup() {
      const { x, y } = userMouse()
      return {
        x,
        y,
      }
    },
    tempate: `{{ x }} {{ y }}`,
  }

  createApp(App).mount('#app')
</script>