1

I set up a flag foundInBrowser that informs me whether the entry 'aaa' is present in localStorage. Clicking on an input toggle adds/removes the entry, which in turn automatically updates the flag:

<template>
  <q-toggle 
    v-model="foundInBrowser" 
    checked-icon="check" 
    color="red"
    :label="`${foundInBrowser ? '' : 'not'} registered in browser`" 
    unchecked-icon="clear"
    @click="registerInBrowser" 
  />
</template>

<script>
    const registerInBrowser = () => {
        // toggle the existance of the localstorage entry
        if (foundInBrowser.value) {
            localStorage.removeItem('aaa')
        } else {
            localStorage.setItem('aaa', person.value?.ID as string)
        }
    }
    const foundInBrowser = computed(() => localStorage.getItem('aaa') !== null)
</script>

When clicking on the toggle, I get an error in the console:

Write operation failed: computed value is readonly

I do not understand this error: I am not trying to write to foundInBrowser anywhere.

2
  • Notice that LS is not reactive and putting it to a computed doesn't make much sense. You need to use reactive state as single source of truth and sync the storage with it, not the opposite way. Since LS is global for a site, it makes sense to use global state with persistent plugin Commented Jul 15, 2023 at 10:33
  • @EstusFlask: ah, you are right. I finally architectured the whole thing around (to get to what you recommended) Commented Jul 15, 2023 at 15:05

1 Answer 1

2

It's pretty much what it says it is. You are putting a computed into a v-model:

<q-toggle 
    v-model="foundInBrowser" 

Since v-model is two-way binding, the q-toggle will write back to it, which fails with the error since you cannot write to a regular computed.


Either turn it into a one-way binding by binding only to modelValue:

<q-toggle 
    :modelValue="foundInBrowser" 

or turn your computed into a writable computed:

const foundInBrowser = computed({
  get(){
    return localStorage.getItem('aaa') !== null
  },
  set(newValue){
     // probably set or delete 'aaa' according to newValue?
  }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.