2
votes

Please see below code.

<template>
  <div v-for="item in arr" :key="item">{{ item }}</div>
</template>

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

export default {
  name: "TestArr",
  setup() {
    const arr = [];
    arr.push(ref("a"));
    arr.push(ref("b"));
    arr.push(ref("c"));
    return { arr };
  }
};
</script>

And the output is below

{ "_rawValue": "a", "_shallow": false, "__v_isRef": true, "_value": "a" }
{ "_rawValue": "b", "_shallow": false, "__v_isRef": true, "_value": "b" }
{ "_rawValue": "c", "_shallow": false, "__v_isRef": true, "_value": "c" }

expected output

a
b
c

I have to call item.value in the template to make it work. What's the work around for this sinario for vue3?

Cheers!

3
The array itself should be a ref not the array itemsHusam Ibrahim

3 Answers

8
votes

You are doing it wrong; try following

setup() {
    const arr = ref([]);
    arr.value.push("a");
    arr.value.push("b");
    arr.value.push("c");
    return { arr };
  }

Their is no point adding ref items in normal array. the Array should be ref.

2
votes

They should be accessed using value field :

  setup() {
    const arr = [];
    arr.push(ref("a").value);
    arr.push(ref("b").value);
    arr.push(ref("c").value);
    return { arr };
  }

but this is a bad practice, your should define your array as ref then push values to it :

  setup() {
    const arr = ref([]);
    arr.push("a");
    arr.push("b");
    arr.push("c");
    return { arr };
  }

another crafted solution is to init the array with that values :

  setup() {
    const arr = ref(["a","b","c"]);
   
    return { arr };
  }
0
votes

This is the correct answer

setup() {
    const arr = ref([]);
    arr.value.push("a");
    arr.value.push("b");
    arr.value.push("c");
    console.log(arr.value)
    return { arr };
  }

This option is possible, but the first is much better.

const arr = reactive([]);
      arr.push("a")
      arr.push("b")
      arr.push("c")
      console.log(arr)