In Vue js, how to assign a unique ID that does not reset on page reload
P粉354602955
P粉354602955 2024-01-29 12:23:08
0
1
446

I am developing a small project to learn Vue js. It should be a habit tracker. I currently have a bug where if you reload the page and add a new custom, my functionality that is supposed to change the background won't work properly.

The error is shown here This is what my array looks like:

0
: 
{id: 0, title: "1", ready: false}

1
: 
{id: 1, title: "123", ready: false}

2
: 
{id: 2, title: "123", ready: false}

3
: 
{id: 0, title: "123", ready: true}

I understand why it doesn't work, because I use a counter to assign the id, which resets to 0 on reload.

<div class="q-pa-md" v-for="(habit, index) in habits" :key="habit.id">
    <q-card class="my-card" :id="habit.id" ref="card">
      <q-card-section>
        <q-checkbox
          id="checkbox"
          v-model="habit.ready"
          @click="changeToTransparent(habit)"
        >
        </q-checkbox>
        {{ habit.title }}

        <q-btn-dropdown flat class="more" icon="more_horiz">
          <q-list>
            <q-item clickable v-close-popup @click="deletehabit(index)">
              <q-item-section>
                <q-item-label>Delete</q-item-label>
              </q-item-section>
            </q-item>

            <q-item clickable v-close-popup @click="edithabitbutton(index)">
              <q-item-section>
                <q-item-label>Edit</q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-btn-dropdown>
      </q-card-section>
    </q-card>
    <div>

let counter = 0;
const habits = ref([]);


const addHabit = () => {
  
  habits.value.push({ id: counter++, title: habittitle.value, ready: false });
  savetolocalstorage();
  habittitle.value = "";
};

const changeToTransparent = (habit) => {

  if(document.getElementById(habit.id) != null) {
    if (habit.ready) {
    document.getElementById(habit.id).style.backgroundColor =
      "rgba(170,193,200,0.25)";
    savetolocalstorage();
  } else {
    document.getElementById(habit.id).style.backgroundColor = "";
    savetolocalstorage();
  }
  }
 
}

Any ideas on how to solve this problem?

P粉354602955
P粉354602955

reply all(1)
P粉986937457

You need to load local storage and set the length to the counter value. I've made a working example here. I also improved your code to make it more consistent with Vue concepts. As @Rahul Purohit pointed out, the JSON.stringify result is required when saving and JSON.parse is required when loading.



sssccc
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template