Vuejs2 Vue:v-if;TypeError:无法读取属性';长度';“未定义”的定义;

Vuejs2 Vue:v-if;TypeError:无法读取属性';长度';“未定义”的定义;,vuejs2,axios,Vuejs2,Axios,我有一个Rails 5.1.6 api,它为端点提供以下数据: 我正在尝试使用axios将实体数据检索到Vue.js,但到目前为止,虽然没有抛出错误,但数据没有显示在视图中。以下是相关文件: #src/components/Entities.vue <template> <div class="entities"> <h1>Entities</h1> <div v-if="entities.length > 0"

我有一个Rails 5.1.6 api,它为端点提供以下数据:

我正在尝试使用axios将实体数据检索到Vue.js,但到目前为止,虽然没有抛出错误,但数据没有显示在视图中。以下是相关文件:

#src/components/Entities.vue
<template>
  <div class="entities">
    <h1>Entities</h1>
    <div v-if="entities.length > 0" class="table-wrap">
      <div>
        <router-link v-bind:to="{ name: 'NewEntity' }" class="">Add Entity</router-link>
      </div>
      <table>
        <tr>
          <td>Title</td>
          <td width="550">Description</td>
          <td width="100" align="center">Action</td>
        </tr>
        <tr v-for="entity in entities">
          <td>{{ entity.title }}</td>
          <td>{{ entity.description }}</td>
          <td align="center">
            <router-link v-bind:to="{ name: 'EditEntity', params: { id: entity._id } }">Edit</router-link> |
            <a href="#" @click="deleteEntity(entity._id)">Delete</a>
          </td>
        </tr>
      </table>
    </div>
    <div v-else>
      There are no entities.. Lets add one now <br /><br />
      <router-link v-bind:to="{ name: 'NewEntity' }" class="add_entity_link">Add Entity</router-link>
    </div>
  </div>
</template>


<script>
import EntitiesService from '@/services/EntitiesService'
export default {
  name: 'entities',
  data () {
    return {
      entities: []
    }
  },
  mounted () {
    this.getEntities()
  },
  methods: {
    async getEntities () {
      const response = await EntitiesService.fetchEntities()
      this.entities = response.data.entities
    }
  }
}
</script>


#src/services/EntitiesService.js:

import Api from '@/services/Api'

export default {
  fetchEntities () {
    return Api().get('/entities')
  }

}

#src/services/Api.js

mport axios from 'axios'

export default() => {
  return axios.create({
    baseURL: 'http://localhost:3000'
  })
}



#Railsapp/config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:3000'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end
,现在我明白了:

vue.esm.js?efeb:591 [Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined"

found in

---> <Entities> at src/components/Entities.vue
       <App> at src/App.vue
         <Root>
warn @ vue.esm.js?efeb:591
logError @ vue.esm.js?efeb:1737
globalHandleError @ vue.esm.js?efeb:1732
handleError @ vue.esm.js?efeb:1721
Vue._render @ vue.esm.js?efeb:4546
updateComponent @ vue.esm.js?efeb:2788
get @ vue.esm.js?efeb:3142
run @ vue.esm.js?efeb:3219
flushSchedulerQueue @ vue.esm.js?efeb:2981
(anonymous) @ vue.esm.js?efeb:1837
flushCallbacks @ vue.esm.js?efeb:1758
Promise.then (async)
microTimerFunc @ vue.esm.js?efeb:1806
nextTick @ vue.esm.js?efeb:1850
queueWatcher @ vue.esm.js?efeb:3068
update @ vue.esm.js?efeb:3209
notify @ vue.esm.js?efeb:697
reactiveSetter @ vue.esm.js?efeb:1014
proxySetter @ vue.esm.js?efeb:3300
_callee$ @ Entities.vue?716d:47
tryCatch @ runtime.js?4a57:62
invoke @ runtime.js?4a57:296
prototype.(anonymous function) @ runtime.js?4a57:114
step @ asyncToGenerator.js?7b11:17
(anonymous) @ asyncToGenerator.js?7b11:28
Promise.then (async)
step @ asyncToGenerator.js?7b11:27
(anonymous) @ asyncToGenerator.js?7b11:35
F @ _export.js?90cd:36
(anonymous) @ asyncToGenerator.js?7b11:14
getEntities @ Entities.vue?716d:45
mounted @ Entities.vue?716d:42
callHook @ vue.esm.js?efeb:2921
insert @ vue.esm.js?efeb:4158
invokeInsertHook @ vue.esm.js?efeb:5960
patch @ vue.esm.js?efeb:6179
Vue._update @ vue.esm.js?efeb:2660
updateComponent @ vue.esm.js?efeb:2788
get @ vue.esm.js?efeb:3142
Watcher @ vue.esm.js?efeb:3131
mountComponent @ vue.esm.js?efeb:2795
Vue.$mount @ vue.esm.js?efeb:8540
Vue.$mount @ vue.esm.js?efeb:10939
Vue._init @ vue.esm.js?efeb:4640
Vue @ vue.esm.js?efeb:4729
(anonymous) @ main.js?1c90:10
./src/main.js @ app.js:1826
__webpack_require__ @ app.js:679
fn @ app.js:89
0 @ app.js:1859
__webpack_require__ @ app.js:679
(anonymous) @ app.js:725
(anonymous) @ app.js:728
vue.esm.js?efeb:1741 TypeError: Cannot read property 'length' of undefined
    at Proxy.render (eval at ./node_modules/vue-loader/lib/template-compiler/index.js?{"id":"data-v-23d09f71","hasScoped":false,"transformToRequire":{"video":["src","poster"],"source":"src","img":"src","image":"xlink:href"},"buble":{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./src/components/Entities.vue (app.js:1661), <anonymous>:8:18)
    at VueComponent.Vue._render (vue.esm.js?efeb:4544)
    at VueComponent.updateComponent (vue.esm.js?efeb:2788)
    at Watcher.get (vue.esm.js?efeb:3142)
    at Watcher.run (vue.esm.js?efeb:3219)
    at flushSchedulerQueue (vue.esm.js?efeb:2981)
    at Array.eval (vue.esm.js?efeb:1837)
    at flushCallbacks (vue.esm.js?efeb:1758)`
    enter code here
vue.esm.js?efeb:591[vue warn]:呈现错误:“TypeError:无法读取未定义的属性'length'”
发现于
--->位于src/components/Entities.vue
在src/App.vue
warn@vue.esm.js?efeb:591
logError@vue.esm.js?efeb:1737
globalHandleError@vue.esm.js?efeb:1732
handleError@vue.esm.js?efeb:1721
Vue._render@Vue.esm.js?efeb:4546
updateComponent@vue.esm.js?efeb:2788
获取@vue.esm.js?efeb:3142
运行@vue.esm.js?efeb:3219
flushSchedulerQueue@vue.esm.js?efeb:2981
(匿名)@vue.esm.js?efeb:1837
flushCallbacks@vue.esm.js?efeb:1758
Promise.then(异步)
microTimerFunc@vue.esm.js?efeb:1806
nextTick@vue.esm.js?efeb:1850
queueWatcher@vue.esm.js?efeb:3068
更新@vue.esm.js?efeb:3209
通知@vue.esm.js?efeb:697
reactiveSetter@vue.esm.js?efeb:1014
proxySetter@vue.esm.js?efeb:3300
_被调用方$@Entities.vue?716d:47
tryCatch@runtime.js?4a57:62
调用@runtime.js?4a57:296
原型。(匿名函数)@runtime.js?4a57:114
步骤@asyncToGenerator.js?7b11:17
(匿名)@asyncToGenerator.js?7b11:28
Promise.then(异步)
步骤@asyncToGenerator.js?7b11:27
(匿名)@asyncToGenerator.js?7b11:35
F_export.js?90cd:36
(匿名)@asyncToGenerator.js?7b11:14
getEntities@Entities.vue?716d:45
安装在实体上。vue?716d:42
callHook@vue.esm.js?efeb:2921
插入@vue.esm.js?efeb:4158
invokeInsertook@vue.esm.js?efeb:5960
补丁@vue.esm.js?efeb:6179
Vue._update@Vue.esm.js?efeb:2660
updateComponent@vue.esm.js?efeb:2788
获取@vue.esm.js?efeb:3142
Watcher@vue.esm.js?efeb:3131
mountComponent@vue.esm.js?efeb:2795
Vue.$mount@Vue.esm.js?efeb:8540
Vue.$mount@Vue.esm.js?efeb:10939
Vue._init@Vue.esm.js?efeb:4640
Vue@Vue.esm.js?efeb:4729
(匿名)@main.js?1c90:10
/src/main.js@app.js:1826
__webpack_require__@app.js:679
fn@app.js:89
0@app.js:1859
__webpack_require__@app.js:679
(匿名)@app.js:725
(匿名)@app.js:728
vue.esm.js?efeb:1741 TypeError:无法读取未定义的属性“length”
在Proxy.render(eval at./node_modules/vue loader/lib/template compiler/index.js?{“id”:“data-v-23d09f71”,“hasScoped”:false,“transformToRequire”:{“video”:[“src”,“poster”],“source”:“src”,“img”:“src”,“image”:“xlink:href”},“buble”:{“transforms”:{.}}/node_modules/vue loader/lib selector.js type=template&index=0!。/src/components/enties.vue(app.js:1661),:8:18)
在VueComponent.Vue.\u渲染(Vue.esm.js?efeb:4544)
位于VueComponent.updateComponent(vue.esm.js?efeb:2788)
at Watcher.get(vue.esm.js?efeb:3142)
at Watcher.run(vue.esm.js?efeb:3219)
在flushSchedulerQueue上(vue.esm.js?efeb:2981)
at Array.eval(vue.esm.js?efeb:1837)
在刷新回调时(vue.esm.js?efeb:1758)`
在这里输入代码

如果让我猜的话,你的问题是:

async getEntities () {
  const response = await EntitiesService.fetchEntities()
  this.entities = response.data.entities // 
}
response.data
可能存在,但
response.data
似乎不太可能有一个名为
entities
的键。在服务层中,您没有做任何事情来将
response.data
中的简单数组封送到
entities

可能是这样的:

async getEntities () {
  const response = await EntitiesService.fetchEntities()
  this.entities = response.data // looks like your array is probably here 
}
在任何情况下,此错误:

“TypeError:无法读取未定义的属性'length'”


很可能是想告诉您,
这个。实体
已被分配到Vue组件中的
未定义的
。解决这个问题。

在开发者控制台的“网络”选项卡下,您能看到对rails应用程序的请求吗?忘了检查那里。
访问XMLHttpRequest at'http://localhost:3000/entities"从源头上说, 'http://localhost:8080'已被CORS策略阻止:请求的资源上不存在'Access Control Allow Origin'标头。createError.js?16d0:16未捕获(承诺中)错误:XMLHttpRequest.handleError(xhr.js?ec6c:87)处createError(createError.js?16d0:16)处的网络错误
。我看看是不是这样。这是最肯定的!你需要在rails应用程序中添加适当的CORS头,以便它能够访问初始化器中的端点更新CORS,现在我明白了:当你这样说时似乎很简单…认真地说。问题解决了。尝试学习javascript和Api消费。这节省了给我很多时间,谢谢!
async getEntities () {
  const response = await EntitiesService.fetchEntities()
  this.entities = response.data // looks like your array is probably here 
}