vue快速入门的三个小实例_vue 3s composition api快速入门指南

vue快速入门的三个小实例

We can now get our hands dirty and start confidently fiddling around with the Composition API to write better maintainable and reusable code.

现在,我们可以动手做,开始自信地摆弄Composition API,以编写更好的可维护性和可重用性的代码。

The Composition API is hands down the bread-and-butter feature of this release, and there are several great articles that explain the motivations and benefits over the “old” options API. There’s even a video course on the topic.

Composition API是此版本的基本功能,并且有几篇很棒的文章解释了“旧”选项API的动机好处。 甚至还有关于该主题的视频课程

This guide is aimed at developers who have already an idea of the Composition API and want to get started rapidly.

本指南面向已对Composition API有所了解并希望快速入门的开发人员。

心态和心理模型 (Mindset and Mental Model)

Before we jump straight into the code examples, let's recap what the Composition API is.

在我们直接进入代码示例之前,让我们回顾一下什么是Composition API。

It’s a purely additive and recommended replacement for mixins. Designed for logic organization, encapsulation, and code reuse, this API comes with complete TS support.

它是纯添加剂,建议替代mixins。 该API专为逻辑组织,封装和代码重用而设计,具有完整的TS支持。

建立 (Setup)

The setup function is the entry point of your component. It’s where you compose your component’s functionality and expose any variable or method to your template or render function.

setup功能是组件的入口点。 在这里,您可以组合组件的功能,并向模板或渲染函数公开任何变量或方法。

<template>
  {{ stuff }}
</template>
<script>
export default {
  setup() {
    const stuff = 'Hello w0rld';
    return {
      stuff
    };
  }
};
</script>

The setup function is called before the beforeCreated lifecycle hook and hence does not have access to the this you’d usually expect.

setup功能的调用之前beforeCreated生命周期挂钩,因此没有进入this你通常会期望。

It receives props and context as arguments.

它接收propscontext作为参数。

Note: The props object is reactive and destructing it will make it lose its reactivity.

注意: props对象是React性的,对其进行破坏会使其失去React性。

Just like a regular function, in order to make it asynchronous, you prepend the method declaration with async. This plays fantastically with the new Suspense feature, which you can read more about in the documentation.

就像常规函数一样,为了使其异步,您可以在方法声明之前加上async 。 这与新的Suspense功能配合使用非常Suspense ,您可以在文档中了解更多信息。

<template> {{ stuff }} - {{ props.msg }} </template>
<script>
export default {
  props: {
    msg: String
  },
  setup(props) {
    const stuff = await getStuffFromApi();
    return {
      stuff,
      props
    };
  }
};
</script>

If you are using Vue’s SFC, you can leverage the syntactical sugar RFC and expose variables to the template as follows:

如果您使用的是Vue的SFC,则可以利用语法糖RFC并将变量公开给模板,如下所示:

<template>
  {{ stuff }}
</template>


<script setup>
export const stuff = 'Hello Vue, One Piece';
</script>

React性(Reactivity)

One of the many exciting things in Vue 3 is the new reactivity system. It is not only abstracted into a separate package but also solves some caveats when it comes to interacting with Arrays or Objects in Vue 2

Vue 3中许多令人兴奋的事情之一是新的React系统。 它不仅被抽象到单独的程序包中,而且还解决了与Vue 2中的数组或对象进行交互时的一些警告。

(State)

Now that we understand how to pass variables from the setup method to the template, let’s take a glimpse at how we can define a reactive variable.

现在,我们了解了如何将变量从setup方法传递到模板,让我们看一下如何定义React式变量。

Previously, using the Options API, you would define that in the data option. Now you’ve got two options: refor reactive.

以前,您可以使用Options API在data选项中进行定义。 现在,您有两个选择: refreactive

Both allow you to create a reactive reference to an object or primitive data.

两者都允许您创建对对象或原始数据的React性引用。

Due to how JavaScript works, primitive types such as string, number, and boolean are passed by value, while objects and arrays are passed by reference — hence the introduction of ref.

由于JavaScript的工作方式,原始类型(例如stringnumberboolean通过值传递,而对象和数组通过引用传递-因此引入了ref

Accordingly, you can use ref for primitive and reactive for objects.

因此,您可以将ref用于原始对象,将reactive用于对象。

<script setup>
import { ref, reactive } from 'vue';

export const firstName = ref('Evan');
export const lastName = ref('You');
// or
export const name = reactive({
  first: 'Evan',
  last: 'You'
});
</script>

Note: refs are always wrapped in an object, so if you want to access the value in your setup method, you have to access .value like this:firstName.value = 'Batman'.

注意: refs总是包装在一个对象中,因此,如果要访问setup方法中的值,则必须访问.value如下所示: firstName.value = 'Batman'

已计算 (Computed)

There is not much changed here. It works as you would expect.

这里没有太多变化。 它可以像您期望的那样工作。

import { computed, ref } from 'vue';


const firstName = ref('Bugs');
const lastName = ref('Bunny');


const captializedName = computed(() =>
  `${firstName.value} ${lastName.value}`.toUpperCase()
);


// / with setters and getters
const fullName = computed({
  get: () => `${firstName.value} ${lastName.value}`,
  set: name => {
    const names = name.split(' ');
    firstName.value = names[0];
    lastName.value = names[names.length - 1];
  }
});


console.log(fullName.value); // Bugs Bunny
console.log(captializedName.value); // BUGS BUNNY
fullName.value = 'Micky Mouse';
console.log(firstName.value); //  Micky

观察者(Watchers)

Similarly to the Options API, you can watch other properties.

与Options API相似,您可以观察其他属性。

import { watch } from 'vue'watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
/* react to change */
})

方法 (Methods)

In order to create a method, you just write a regular JavaScript function. Just confirm that you return or export the function if you want it to be available in your template.

为了创建一个方法,您只需编写一个常规JavaScript函数。 如果希望模板中可用该功能,只需确认您returnexport该功能即可。

<template>
  <div @click="doubleCount">{{ count }}</div>
</template>


<script setup>
import { ref } from 'vue';
export const count = ref(1);
export function doubleCount() {
  count.value *= 2;
}
</script>

模板参考(Template refs)

As mentioned earlier, there is no this and therefore you might be wondering how to access this.$refs.

如前所述,没有this ,因此您可能想知道如何访问this.$refs

<template>
  <input ref="root" />
</template>
<script setup>
import { ref, onMounted } from 'vue';

export const root = ref(null);
onMounted(() => {
  root.value.placeholder = 'type here';
});
</script>

生命周期挂钩(Lifecycle hooks)

You can access all the lifecycle hooks except created and beforeCreated by calling onMounted and onXXX.

您可以访问所有的生命周期挂钩,除了createdbeforeCreated通过调用onMountedonXXX

import { onMounted, onUnmounted } from 'vue'onMounted(() => { /* do stuff here */ }

创建可组合 (Creating a composable)

We have seen how to use the new Composition API. Let’s explore how can we use it to compose components.

我们已经看到了如何使用新的Composition API。 让我们探索如何使用它来组成组件。

Assuming that we want to reuse the mouse X and Y values across several components, we can write a simple composable.

假设我们想在多个组件之间重用鼠标XY值,我们可以编写一个简单的可组合对象。

import { ref, onMounted, onUnmounted } from 'vue';


export function useMousePosition() {
  const x = ref(0);
  const y = ref(0);


  function update(e) {
    x.value = e.pageX;
    y.value = e.pageY;
  }


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


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


  return {
    x,
    y
  };
}

Then we can consume this composable in our component.

然后,我们可以在组件中使用此可组合项。

<template> {{ x }}, {{ y }} </template><script setup>
import { useMousePosition } from './useMousePosition';export const { x, y } = useMousePosition();
</script>

实践与贡献 (Practice and Contribute)

Now that we have covered the basics, you can start fiddling around and create some composables.

既然我们已经介绍了基础知识,您就可以开始摆弄并创建一些可组合的东西。

It’s also an amazing opportunity to contribute to open source, as there are not many composables yet. If you want some inspiration, you can take a look at react-use and port some of the hooks to this package.

这也是一个为开源做出贡献的绝佳机会,因为目前还没有太多可组合的东西。 如果您需要一些启发,可以看一下React-use的用法,并将某些挂钩移植到此程序包中。

其他资源 (Additional Resources)

Here is a list of useful resources regarding Vue 3’s composition API:

以下是有关Vue 3的Composition API的有用资源的列表:

I hope you found this guide helpful. Thanks for reading and enjoy Vue 3!

希望本指南对您有所帮助。 感谢您阅读并享受Vue 3!

翻译自: https://medium.com/better-programming/the-quick-start-guide-for-vue-3s-composition-api-fc0913fa9d97

vue快速入门的三个小实例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值