首先推荐基本数据类型使用ref定义,引用数据类型使用reactive定义

现在官网推荐使用ref定义所有变量

但是ref也可以定义引用数据类型,如果使用ref定义引用数据类型

首先需要先从vue解构

import {reactive, ref } from "vue";

定义数据

let state = reactive({    //使用reactive定义数据,需要写成对象的格式
  global: [],
});
let arr = reactive([])      //用reactive只定义一个空数组
let test = ref([]);       //使用ref定义数据,直接定义即可
let testObj = ref({});

数据赋值

// 获取所有商品
  productAll().then(res => {

    state.global=res.product     //用reactive定义的直接赋值即可

    arr.push(...[1,2,3])         //用reactive单个定义的数组,通过扩展运算符,和push赋值  
    
    test.value = res.product;    //使用ref定义的,需要在定义的变量后边加.value

    testObj.value = res.product[0];
     
  });

在模板区使用,reactive需要用定义的数据区,去找到需要用到的数据

<template v-for="(item, index) in state.global" :key="index">
   <div>购买数量{{ item.buyCount }}</div>
</template>

在模板区使用,ref,直接使用定义的变量即可,不需要.value

<template v-for="(item, index) in test" :key="index">
    <div class="test" @click="numClick(index)">
      {{ item.uid }}-{{ item.proDescription }}
    </div>
</template>

操作数据中的数据

// 用reactive定义的
function getCount(event, index) {
  state.global[index].buyCount = event;
}

// 用ref定义的,需要用.value
function numClick(index) {
  test.value[index].uid++;
}

总结:JS区操作

                定义数据

                        reactive定义时,需要写成对象的格式,(定义的单个数据不需要)

                        ref定义时,直接定义即可

                操作数据

                        用reactive定义的数据,直接操作即可,

                        用reactive定义的单个数据,需要使用扩展运算符和push或pop给数据赋值

                        用ref定义是数据,需要在定义的变量后边加.value

          模板区

                用reactive定义的数据,需要用定义时的变量到所需的变量

                用ref定义的变量,直接使用变量即可,不需要使用.value

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐