迁移从Vue 2到Vue 3 – 如何在Vue 3的setup API中更新Vue 2组件中添加的混入。

huangapple go评论63阅读模式
英文:

Migartion of vue2 to vue 3 - how to update the mixins added in vue2 components in vue3 setup api

问题

我们最近开始将我们的应用从vue2迁移到vue3,一些组件已经添加了mixins,我想知道如何在vue 3中添加这些mixins。

我尝试了几种解决方案,但找不到像vue 2中可用的特殊hook。

export default {
  name: "Modal",
  components: { Loader },
  mixins: []
}
```如何添加mixins?

<details>
<summary>英文:</summary>

We have been lately started migration of our app to vue 3 from vue2 and some components have mixins added and i was wondering how can i add this in vue 3

I tried several solutions on this and couldn&#39;t find any special hook as available in vue 2

export default {
  name: &quot;Modal&quot;,
  components: { Loader },
  mixins: []
}`how can i add mixins`

</details>


# 答案1
**得分**: 0

In Vue 3, you can still use mixins in a similar way to Vue 2 when using the Options API:

    const mixin = {
      created() { console.log('Mixin'); },
    };
    
    export default {
      name: "Modal",
      components: { Loader },
      mixins: [mixin]
    };

But as for the Composition API, you have to use composable functions instead:

    // Composable declaration function
    import { onMounted } from 'vue';
    
    export function useMixin() {
      onMounted(() => console.log('Mixin'));
      return {};
    }
    
    // In your component
    import { useMixin } from './mixin';
    import Loader from './Loader';
    
    export default {
      name: "Modal",
      components: { Loader },
      setup() {
        useMixin();
        return {};
      },
    };

Composable functions provide a more explicit and flexible alternative to mixins when using Vue 3's Composition API.

<details>
<summary>英文:</summary>

In Vue 3, you can still use mixins in a similar way to Vue 2 when using the Options API:

    const mixin = {
      created() { console.log(&#39;Mixin&#39;); },
    };
    
    export default {
      name: &quot;Modal&quot;,
      components: { Loader },
      mixins: [mixin]
    };

But as for the Composition API, you have to use composable functions instead:

    // Composable declaration function
    import { onMounted } from &#39;vue&#39;;
    
    export function useMixin() {
      onMounted(() =&gt; console.log(&#39;Mixin&#39;));
      return {};
    }
    
    // In your component
    import { useMixin } from &#39;./mixin&#39;;
    import Loader from &#39;./Loader&#39;;
    
    export default {
      name: &quot;Modal&quot;,
      components: { Loader },
      setup() {
        useMixin();
        return {};
      },
    };

Composable functions provide a more explicit and flexible alternative to mixins when using Vue 3&#39;s Composition API.

</details>



huangapple
  • 本文由 发表于 2023年7月18日 15:38:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710487.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定