vue3中的setup函数如何使用

发布时间:2022-04-24 10:52:25 作者:zzz
来源:亿速云 阅读:447

Vue3中的setup函数如何使用

Vue3引入了Composition API,其中setup函数是Composition API的核心部分。setup函数在组件实例创建之前执行,用于替代Vue2中的datamethodscomputed等选项。本文将详细介绍setup函数的使用方法。

1. setup函数的基本用法

setup函数是Vue3组件中的一个新的生命周期钩子,它在组件实例创建之前执行。setup函数接收两个参数:

setup函数返回一个对象,该对象的属性将暴露给模板使用。

import { ref } from 'vue';

export default {
  props: {
    message: String
  },
  setup(props, context) {
    const count = ref(0);

    function increment() {
      count.value++;
    }

    return {
      count,
      increment
    };
  }
};

在上面的例子中,setup函数返回了一个包含countincrement的对象,这些属性和方法可以在模板中直接使用。

2. 响应式数据

setup函数中,可以使用refreactive来创建响应式数据。

2.1 ref

ref用于创建一个响应式的引用值,通常用于基本类型的数据(如StringNumberBoolean等)。

import { ref } from 'vue';

export default {
  setup() {
    const count = ref(0);

    return {
      count
    };
  }
};

在模板中使用count时,需要通过count.value来访问其值。

2.2 reactive

reactive用于创建一个响应式的对象,通常用于复杂类型的数据(如ObjectArray等)。

import { reactive } from 'vue';

export default {
  setup() {
    const state = reactive({
      count: 0,
      message: 'Hello Vue3'
    });

    return {
      state
    };
  }
};

在模板中可以直接访问state对象的属性。

3. 生命周期钩子

setup函数中,可以使用onMountedonUpdatedonUnmounted等生命周期钩子。

import { onMounted, onUnmounted } from 'vue';

export default {
  setup() {
    onMounted(() => {
      console.log('Component is mounted!');
    });

    onUnmounted(() => {
      console.log('Component is unmounted!');
    });
  }
};

4. watchcomputed

setup函数中,可以使用watchcomputed来监听数据变化和计算属性。

4.1 watch

watch用于监听响应式数据的变化。

import { ref, watch } from 'vue';

export default {
  setup() {
    const count = ref(0);

    watch(count, (newValue, oldValue) => {
      console.log(`count changed from ${oldValue} to ${newValue}`);
    });

    return {
      count
    };
  }
};

4.2 computed

computed用于创建计算属性。

import { ref, computed } from 'vue';

export default {
  setup() {
    const count = ref(0);
    const doubleCount = computed(() => count.value * 2);

    return {
      count,
      doubleCount
    };
  }
};

5. emit事件

setup函数中,可以使用context.emit来触发自定义事件。

export default {
  setup(props, context) {
    function handleClick() {
      context.emit('custom-event', 'Hello from child');
    }

    return {
      handleClick
    };
  }
};

在父组件中监听custom-event事件即可接收到子组件传递的数据。

6. 总结

setup函数是Vue3中Composition API的核心,它提供了一种更灵活的方式来组织组件的逻辑。通过setup函数,我们可以更方便地管理响应式数据、生命周期钩子、计算属性、监听器等。掌握setup函数的使用,能够帮助我们编写更加模块化和可维护的Vue3组件。

推荐阅读:
  1. 怎么在vue3中使用setup、 ref、reactive
  2. 如何在vue3中使用setup、 ref、reactive

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue3 setup

上一篇:vue props type怎么设置多个类型

下一篇:vue如何axios整合使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》