1

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

componentArgs is an array where index 0 is the component name so !!this.$options.components[ componentArgs[0] ] worked for me.

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.