0
votes

I want to cache state inside a handler passed by props.

Problem is, the template renders and text content changes well, but the console always throw error:

[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'apply' of undefined"

Codes below:

<template>
  <picker-box :options="item.options" @change="handlePickerChange($event, item)">
    <text>{{ item.options[getPickerValue(item)].text }}</text>
  </picker-box>
</template>

<script>
  export default {
    props: {
      item: {
        type: Object,
        default() {
          return {
            options: [{ text: 'op1' }, { text: 'op2' }],
            handler: {
              current: 0,
              get() {
                return this.current
              },
              set(value) {
                this.current = value
              },
            },
            /* I also tried this: */
            // new (function () {
            //   this.current = 0
            //   this.get = () => {
            //     return this.current
            //   }
            //   this.set = (value) => {
            //     this.current = value
            //   }
            // })(),
          }
        },
      },
    },
    methods: {
      handlePickerChange(value, item) {
        item.handler.set(value)
      },
      getPickerValue(item) {
        return item.handler.get()
      },
    },
  }
</script>

I know it's easy using data() or model prop, but I hope to cahce as this handler.current, in other words, I just want to know why this handler object isn't correct (syntax layer), how can I fix it.

1

1 Answers

0
votes

What exactly state are you trying pass? If you need to keep track of a static property, you could use client's localstorage, or a watcher for this. If you need to keep of more dynamic data, you could pass it to a computed property that keeps track and sets them everytime they change.