Vue 3 引入了一个新的组合式 API,旨在提供一种更灵活和模块化的方式来编写组合逻辑。setup 函数是该 API 的核心部分,它被用于替代 Vue 2.x 中的选项式 API。本文将详细介绍Vue 3中的 setup 函数,描述其作用,同时提供示例代码来帮助理解。

什么是 setup 函数?

setup 函数是 Vue 3 组合式 API 的入口点。当一个组件实例被创建时,setup 函数会在组件被解析之前(以及 datacomputedmethods 被处理之前)被调用。它是处理组件逻辑的主要地方,返回的数据和方法可以直接在模板中使用。

<template>
  <div>{{ message }}</div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const message = ref('Hello Vue 3');

    return {
      message
    };
  }
}
</script>

在这个简单的示例中,setup 函数返回了一个包含 message 的对象,并且 message 使用了 Vue 的 ref 创建了一个响应式数据。在模板中,我们可以像正常使用 Vue 数据一样使用它。

setup 函数的参数

setup 函数接收两个参数:propscontext

props

props 参数允许我们访问传递给组件的属性。它是一个响应式对象,这意味着你可以在 setup 函数中直接使用 props 的属性,并且它们会自动响应变化。

<template>
  <div>{{ text }}</div>
</template>

<script>
export default {
  props: {
    text: String
  },
  setup(props) {
    return {
      text: props.text
    };
  }
}
</script>

context

context 参数是一个普通的 JavaScript 对象,包含 attrsslotsemit 三个属性。

  • attrs:包含透传给组件的非 prop 特性。
  • slots:包含传递给组件的插槽内容。
  • emit:一个函数,用于在组件实例上触发事件。

如下示例展示了如何使用 context 参数:

<template>
  <div>{{ contextText }}</div>
</template>

<script>
export default {
  setup(props, context) {
    const contextText = context.attrs.contextText;

    return {
      contextText
    };
  }
}
</>

如果我们在父组件中使用该组件,并传递 attribute:

<template>
  <ChildComponent contextText="Hello from context!" />
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  }
}
</script>

以上代码会在子组件中显示 “Hello from context!”。

使用组合式 API 组织代码

借助 setup 函数和 Vue 3 的组合式 API,我们可以更方便地组织和复用代码。

响应式状态

Vue 3 提供了 refreactive 函数来创建响应式状态。ref 创建一个单值的响应式引用,而 reactive 创建一个复杂对象的响应式代理。

<template>
  <div>{{ counter }}</div>
  <button @click="increment">Increment</button>
</template>

<script>
import { ref } from 'vue';

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

    const increment = () => {
       counter.value++;
    };

    return {
      counter,
      increment
    };
  }
}
</script>

使用 watchwatchEffect

watchwatchEffect 是 Vue 组合式 API 提供的用于监听响应式数据变化的工具。watch 用于监控特定的数据变化,watchEffect 则是自动收集依赖并执行副作用。

<template>
  <div>{{ count }}</div>
</template>

<script>
import { ref, watch, watchEffect } from 'vue';

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

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

    watchEffect(() => {
      console.log(`Count is now ${count.value}`);
    });

    return {
      count
    };
  }
}
</script>

组合函数(Composable Functions)

组合函数是封装和复用逻辑的最佳实践。可以利用 setup 函数将复杂的逻辑分解到独立的组合函数中。

// useCounter.js
import { ref } from 'vue';

export function useCounter() {
  const counter = ref(0);

  const increment = () => {
     counter.value++;
  };

  return {
    counter,
    increment
  };
}

然后在组件中使用它:

<template>
  <div>{{ counter }}</div>
  <button @click="increment">Increment</button>
</template>

<script>
import { useCounter } from './useCounter.js';

export default {
  setup() {
    const { counter, increment } = useCounter();

    return {
      counter,
      increment
    };
  }
}
</script>

这样,通过将常用状态逻辑抽象为组合函数,我们可以在不同的组件中轻松重用逻辑。

总结

Vue 3 的 setup 函数彻底改变了组件状态和逻辑的编写方式。通过可组合的 API,可以更高效地组织代码,增强代码复用性和可读性。


最后问候亲爱的朋友们,并邀请你们阅读我的全新著作

在这里插入图片描述

GitHub 加速计划 / vu / vue
207.53 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 4 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐