ekjcfn3902039
ekjcfn3902039

Reputation: 1839

Referencing components from within a v-stepper

I am using a v-stepper and want to collect results as I go along. At the last stepper I want to use all those results to do something. The pseudo-code looks like this:

// MyStepper.vue
<v-stepper-content step="1">
  <SomeComponent ref="one"/>
  // This works so the ref is valid
  <v-btn text @click="this.$refs.one.runMethod()">Test</v-btn>
  <v-btn text @click="stepperNum++">Next</v-btn>
</v-stepper>
<v-stepper-content step="2">
  <SomeOtherComponent ref="two"/>
  // This works so the ref is valid
  <v-btn text @click="this.$refs.two.runMethod()">Test</v-btn>
  <v-btn text @click="stepperNum++">Next</v-btn>
</v-stepper>
<v-stepper-content step="3">
  <AnotherComponent v-if="canLoad"
   :one="$refs.one.results" 
   :two="$refs.two.results"/>
</v-stepper>

// SomeComponent.vue/SomeOtherComponent.vue
data: function() {
  return {
    results: [],
    stepperNum: 0
  }
}
methods: {
  runMethod() {
    console.log("Clicked");
  }
}
computed: {
  canLoad() {
    return this.stepperNum > 2;
  }
}

// AnotherComponent.vue
props: {
  one: {
    type: Array,
    required: true
  },
  two: {
    type: Array,
    required: true
  }
}

When i run that code I get a 't.$refs.one is undefined' message. I am assuming this is because everything is loading at the same time when the MyStepper.vue page is loaded.

Is there a way to prevent v-steppers from loading their bodies (aka AnotherComponent.vue) until the previous v-stepper has been complete? Is there a different strategy that should be used to achieve the desired functionality?

Update: I decided to watch the results inside the child component, and emit an event. The parent uses the emitted event to control the data and enable/disable next buttons, pass in the results to the third component, etc.

Upvotes: 0

Views: 1152

Answers (1)

Ryo Shiina
Ryo Shiina

Reputation: 568

EDIT: OP confirmed that there's no reactivity when using the refs contents for a computed property. Consider the first code block as a wrong approach. Use regular variables instead of refs.


I guess I would go for a computed property returning true when both refs are loaded:

computed: {
  canLoadThirdStep() {
    return (this.$refs.one && this.$refs.two)
  }
}

Then just use the returned value in a v-if to display AnotherComponent:

<AnotherComponent 
  v-if="canLoadThirdStep" 
  :one="$refs.one.results" 
  :two="$refs.two.results" 
/>

I hope this is what you wanted. Let me know if this works!

Upvotes: 1

Related Questions