1
votes

I have a parent component as shown below that implements dynamic component switching. The challenge is that I want to ensure that the componentArgs name data at index 0 is valid. The line this.components.indexOf(componentArgs[0]) > -1 throws a TypeError.

Parent.vue?e9d7:xx Uncaught TypeError: Cannot read property 'indexOf' of undefined

Clearly, this.components is not the correct way to access the parents components. How do I accomplish this?

<template>
  <component v-bind:is="currentForm" v-on:switchcomponent="switchComponent"></component>            
</template>

<script>
import Login from '@/components/Login'
import Signup from '@/components/Signup'

export default {
  name: 'Parent',
  components: {
    login: Login,
    signup: Signup
  },
  data () {
    return {
      title: 'Sign Up or Login',
      email: '',
      currentForm: 'login'
    }
  },
  methods: {
    switchComponent: function (componentArgs) {
      // componentArgs format: [name, title, email (Use empty string if N/A.)]
      let name = 0
      let title = 1
      let email = 2
      console.log('component: ' + componentArgs)

      if (this.isValidComponent(componentArgs)) {
        this.currentForm = componentArgs[name]
        this.title = componentArgs[title]
        this.email = componentArgs[email]
      }
    },
    isValidComponent: function (componentArgs) {
      let exactLength = 3

      if (componentArgs.length === exactLength) {
        console.log('components ' + this.components)
        if (this.components.indexOf(componentArgs[0]) > -1) {
          console.log('component exists')
          return true
        }

        return false
      }

      return false
    }
  }
}
</script>
1

1 Answers

1
votes

The components property can be accessed from

this.$options.components

So your function could be

isValidComponent(name){
  return !!this.$options.components[name];
}

where name is the name of the component. I can't really tell what you are passing in componentArgs.

Example.