【问题标题】:Getting vue typeerror cannot read property 'name' of undefined获取 vue typeerror 无法读取未定义的属性“名称”
【发布时间】:2019-05-29 13:25:07
【问题描述】:

我知道这种类型的问题无处不在,但我很难找到一个好的答案(我是 VueJS 新手)。对此我很抱歉。

我正在尝试使用 vform 传递数据。

我想要做的是通过 vform 将用户详细信息添加到表中。

这是我的 Users.vue 代码

<div class="modal fade" id="addNew" tabindex="-1" role="dialog" aria-labelledby="addNew" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Add New</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>

          <div class="modal-body">
              <div class="form-group">
              <input v-model="form.name" type="text" name="name"
              class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
              <has-error :form="form" field="name"></has-error>
             </div>
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Save changes</button>
          </div>

        </div>
      </div>
    </div> 

<script>
    export default {
    data(){

        return{

            form: new Form({
                name: ''

            })
        }
    },  
 }
</script>

这是我的 app.js

 require('./bootstrap');

    window.Vue = require('vue');

    import { Form, HasError, AlertError } from 'vform';

    window.form = Form;

    Vue.component(HasError.name, HasError)
    Vue.component(AlertError.name, AlertError)

    import VueRouter from 'vue-router'
    Vue.use(VueRouter)

    let routes = [
      { path: '/dashboard', component: require('./components/Dashboard.vue') },
      { path: '/profile', component: require('./components/Profile.vue') },
      { path: '/users', component: require('./components/Users.vue') }
    ]

    const router = new VueRouter({
      mode: 'history',
      routes // short for `routes: routes`
    })

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    您遇到的问题很可能与此有关:

    <input v-model="form.name" type="text" name="name"
    

    您可以看到它是唯一调用.name 的地方。这意味着您的 form 对象是 undefined 并且代码试图在其上调用属性 name 这会引发错误。

    如果您查看vform README,您会看到import 语句实际上在组件内部。您的代码的问题是 app.js 内部的导入不会神奇地出现在您的组件中,因此您不能在 Vue 组件中执行 new Form() 。虽然您确实将它分配给app.js 中的window 对象,但您以后不要重复使用它和IMO,最好显式导入您的依赖项。

    因此,总而言之,您需要做的是:在 Vue 组件中打开 &lt;script&gt; 标记之后添加此导入语句

    import { Form } from 'vform';
    

    【讨论】:

    • Justin Ho Tuan Duong 非常感谢您的时间和回答。
    猜你喜欢
    • 2021-11-13
    • 2022-01-14
    • 2022-06-22
    • 2015-10-16
    • 2021-12-28
    • 1970-01-01
    • 2020-04-08
    • 2022-06-28
    • 2021-08-16
    相关资源
    最近更新 更多