1、Mixins 代码:
- const myMixin = {
- data() {
- return {
- count: 0
- };
- },
-
- mounted() {
- console.log('Component mounted');
- },
-
- computed: {
- doubleCount() {
- return this.count * 2;
- }
- },
-
- methods: {
- increment() {
- this.count++;
- }
- }
- };
-
- export default {
- mixins: [myMixin]
- }
2、hooks代码
- import { ref, onMounted, computed } from 'vue';
-
- export default {
- setup() {
- const count = ref(0);
-
- onMounted(() => {
- console.log('Component mounted');
- });
-
- const doubleCount = computed(() => count.value * 2);
-
- function increment() {
- count.value++;
- }
-
- return {
- count,
- doubleCount,
- increment
- };
- }
- }
Mixins 是vue2的用法,通过对象的方式进行定义和应用,在组件中的属性和方法会与组件本身的属性和方法进行合并,可能会导致命名冲突或不可预料的行为。
Hooks 是vue3的用法,使用函数的方式定义和使用,可以将相关的逻辑和状态封装为自定义的 Hook 函数,相对来说更安全。