javascript - VueJs 验证父组件中的子组件名称

标签 javascript vue.js vuejs2 vue-component

我有一个如下所示的父组件,它实现了动态组件切换。挑战是我想确保索引 0 处的 componentArgs name 数据有效。 this.components.indexOf(componentArgs[0]) > -1 行抛出 TypeError。

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

显然,this.components 不是访问父组件的正确方法。我该如何实现这个目标?

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

最佳答案

组件属性可以从

访问
this.$options.components

所以你的函数可以是

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

其中 name 是组件的名称。我真的无法判断您在 componentArgs 中传递的内容。

Example .

关于javascript - VueJs 验证父组件中的子组件名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43011477/

相关文章:

javascript - 在作用域链上声明一个变量

php - 使用window.print时如何固定打印区域的大小?

javascript - 我如何才能唯一地选择我当前 Blogger 帖子的本地元素,而不是整个文档中的元素?

javascript - 与跨站点资源关联的 cookie 设置为没有 `SameSite` 属性

javascript - 为什么我的 VueJs 文件 ('*.vue' ) 中的所有 Flow 类型都带有下划线?

ajax - 在 Laravel 5.5 上使用 axios 发布请求

javascript - 视觉 : whitespace when carousel is sliding

vue.js - 有条件地将 @submit.prevent 添加到 Vue.js 中的表单

javascript - API调用后如何渲染数据? (Vue.js)

vuejs2 - Vuex 过滤状态