vue ref :ref_Vue3,使用Ref或Reactive

时间:2024-10-19 14:47:11

In my previous post, I implemented my first Vue3 component.

在上一篇文章中,我实现了我的第一个Vue3组件。

I implementend a very simple web app (roll the dice) where I had a “div” where to show the result and a button to trigger the roll and generate a random number from 1 to 6.

我实现了一个非常简单的Web应用程序(掷骰子),其中有一个显示结果的“ div ”和一个触发掷骰并生成1到6的随机数的按钮。

In that case, I used “ref()” to create reactive properties.

在那种情况下,我使用“ ref() ”来创建React特性。

“My first Vue3 component” article where I used ref() for declaring reactive properties: /swlh/my-first-vue3-component-6e1ef1670544

我使用ref()声明React性的“我的第一个Vue3组件”文章: https :///swlh/my-first-vue3-component-6e1ef1670544

ref()“方法” (The ref() “approach”)

For example in “setup()” function of my component I declared “dice” property in order to store the last result of the roll action.

例如,在我组件的“ setup() ”函数中,我声明了“ dice ”属性,以便存储滚动动作的最后结果。

Image for post

The “dice” property was an integer, initialized with 0. To make it reactive, I used “ref()” function to initialize it. So “dice” it was not just a simple integer but an object:

dice ”属性是一个整数,初始化为0 。 为了使其具有React性,我使用“ ref() ”函数对其进行了初始化。 因此,“ 骰子 ”不仅是一个简单的整数,而且是一个对象:

const dice = ref(0);
Image for post
The property “dice” is not just a simple integer. It is a object with value attribute
属性“骰子”不仅仅是一个简单的整数。 它是具有值属性的对象

In this way “dice” is a object with “value” attribute. This means that, if you want to access to the “dice” value in your component, you need to use “”.

这样,“ 骰子 ”是具有“ ”属性的对象。 这意味着,如果要访问组件中的“ dice ”值,则需要使用“ ”。

从ref()到react() (From ref() to reactive())

Another way to make the properties reactive is to use “reactive()” function.

使属性具有React性的另一种方法是使用“ react() ”函数。

The first difference from developer perspective is that using “ref()” you need to declare each single property

从开发人员的角度来看,第一个区别是使用“ ref() ”时,您需要声明每个属性

const dice = ref(0);
const rolls = ref([]);

and when you send the properties too the template you need to list them individually:

当您也发送属性模板时,您需要单独列出它们:

return { dice, rolls, total, roll, restart };

With “reactive()” function you need to collect all properties in one object:

使用“ react() ”函数,您需要将所有属性收集到一个对象中:

const game = reactive(
{
dice: 0,
rolls: []
}
)

With this syntax you can pass to the template just the object (game object) instead of all properties (dice, rolls…):

使用这种语法,您可以仅将对象(游戏对象)而不是所有属性(骰子,掷骰子……)传递给模板:

return {
game, //data
roll, restart //functions
};

Another difference is in the properties usage. You can avoid to use “.value” but you need to use it as object attribute “”. For example:

另一个不同之处在于属性用法。 您可以避免使用“ .value ”,但需要将其用作对象属性“ ”。 例如:

function restart() {
=0
= [];
}

An additional thing: if you want to avoid to use “” and “” and you want use just “dice” and “rolls”, you could use the object destructuring when you send properties to template (in the return clausole of setup method).

另一件事:如果要避免使用“ ”和“ ”,而只想使用“ dice ”和“ rolls ”,则可以在将属性发送到模板时使用对象分解 (在返回设置方法的步骤)。

模板 (The template)

Thanks to the usage of destructuring object, the template is still the same of “ref()” approach.

由于使用了解构对象,因此模板仍然与“ ref() ”方法相同。

<template>
<h1>Number is: {{ dice }}</h1>
<div>Number of rolls: {{ }}</div>
<div>Total: {{ total }}</div>
<button @click="roll()">Let's roll the dice</button>
<button @click="restart()">Restart</button>
<ul>
<li v-for="(t, index) in rolls" :key="index">
{{ t }}
</li>
</ul>
</template>

遍历代码 (Walking through the code)

<script>
// ##001 : import from vue3:
// - reactive for making properties reactive;
// - computed for computed function like total
// - toRefs for destructuring object for template
import { reactive, computed, toRefs } from "vue";
export default {
name: 'RollTheDiceReactive',
// ##002 : implement setup function
setup() {
// ##003 : declare and initialize reactive object
const game = reactive(
{
dice: 0,
rolls: [],
// ##004 : we include also computed properties in game object
total: computed(
() => {
let temptotal = 0;
for (let i=0 ; i< ; i++) {
temptotal = temptotal + [i]
}
return temptotal;
}
)
}
)
// ##005: implement roll function (inside setup() )
function roll() {
= (() * (5)) + 1;
();
}// ##06: implement restart function (inside setup() )
function restart() {
=0
= [];
}// ##007: expose to the template all stuff (object, functions etc)
return {
...toRefs(game), //data
roll, restart //functions
};
}
}
</script>
  • ##001 import from vue3: reactive (for making properties reactive), computed (for computed functions), toRefs (for destructuring object for template);

    ## 001从vue3导入: React式 (用于使属性具有React性), 计算式 (用于计算函数), toRefs (用于模板的解构对象);

  • ##002 setup function: with composition API in Vue3 we need to implement the setup function. Setup function will contain and will return an object (see point ##007) and functions needed by template;

    ## 002设置功能:在Vue3中使用复合API,我们需要实现设置功能。 设置函数将包含并返回一个对象(请参阅第#007点)和模板所需的函数;
  • ##003 declare the reactive object with properties and also computed properties. To make it reactive we will use “reactive()” function;

    ## 003使用属性和计算属性声明React对象。 为了使其具有React性,我们将使用“ react() ”函数;

  • ##004 we can include also “computed properties” in the reactive object. You can access to computed properties accessing to the object properties ( in this case);

    ## 004我们还可以在React对象中包含“计算属性”。 您可以访问计算属性,而访问对象属性(在这种情况下为 );

  • ##005 implement the roll() function in order to change the value of dice and adding on top of the array rolls the new dice value (to keep track of all rolls);

    ## 005实现roll()函数以更改骰子的值,并在数组的顶部添加新的骰子值(以跟踪所有掷骰 );

  • ##006 implement the restart() function in order to re-initialize “dice” and “rolls” (we are accessing to them as object attribute);

    ## 006实现restart()函数,以便重新初始化“ dice ”和“ rolls ”(我们将它们作为对象属性访问);

  • ##007 this is a new thing for Vue2 users (because the setup() method). We need to return an object with all stuff needed in the template. In order to access directly to attributes in the template as “dice” instead of “” you need to use destricturing functionality (…object). To keep the destructured object reactive, you need to use “…toRef(object)”. If you don’t use “toRef()” and you try to use just“…object”, you will loose the reactivity of the properties.

    ## 007这对Vue2用户来说是新事物(因为setup()方法)。 我们需要返回一个对象,其中包含模板中所需的所有内容。 为了直接以“ dice ”(而不是“ ”)访问模板中的属性,您需要使用限制功能( …object )。 要使已变形的对象保持React状态,您需要使用“ …toRef(object) ”。 如果不使用“ toRef() ”,而仅尝试使用“ …object ”,则会失去属性的React性。