1

I am trying to build a vue component that will e.g. have a button to reset all state inside its slot. To have a "minimal" example, I have here removed styling, extra functionality etc.

E.g. my-reseter-component:

<template>
  <div>
   <slot></slot>
   <v-btn @click="dialog_action_reset()">
  <div>
<template>
<script>  
export default {
  data() { 
    return{ init_state:NaN}
  },
  created:{
    this.init_state=???????? // javascript code to copy data of slot
  },  
  methods: {
    dialog_action_reset() {
      //javascript code to restore from this.init_state
      ????????????
    }
  }

I could then use this as e.g.:

How would I access(read restore) the data inside the slot?

Alternatively, if I am going about this wrong, what would be a valid approach/architecture that would allow me to implement this functionality without having to list all data inside the set of components to be reset?

get-slot-data-as-a-variable-in-vue seems to have much similarity to the reading part of my question, but the solution proposed seems to be specific to the question's part about the specific component(?)

To read, I have tried a lot, including:

            var slot_data = this.$slots['default'][0];
            var slot_data2 =Object.getOwnPropertyDescriptor(slot_data,"componentInstance")

The second line does not work and returns undefined, although in firefoxe's console I can see a property(?) componentInstance that contains my data...(wonder why?)

ntg
  • 12,950
  • 7
  • 74
  • 95

1 Answers1

2

The elements that go into your component slot are effectively coded in the parent, so why don't you just $emit a signal after the button is pressed? This way you don't have to pass any data into the resetter component:

    dialog_action_reset() {
      this.$emit('reset-slot')
    }

Then you listen on this signal in the parent component, and trigger the data reset:

<template>
  <resetter @reset-slot="resetData">
    <div>Foo</div>
  </resetter>
</template>
<script>  
export default {
  data() { 
    return{ some_state: 0 }
  },  
  methods: {
    resetData() {
       this.some_state = 0
    }
  }
blackgreen
  • 34,072
  • 23
  • 111
  • 129