首页 > 解决方案 > 属性或方法 * 未定义。渲染时出错

问题描述

我是 Vue.js 的新手。问题是我无法用 JSON 的值填充表格。控制台显示:

未定义属性或方法“表”

当我点击按钮时,它会说:

未定义属性或方法“allRecords”

我不知道为什么。可能是 index.js 中的问题还是下面代码中的问题?

谢谢

<template>
      <div >
        <input type='button' @click='allRecords()' value='Select All users'>
        <b-table striped hover responsive id="tabla_final" >
          <tr v-for='table in tables'>
                <td>{{ table.sum_real }}</td>
                <td>{{ table.sum_ppto }}</td>
                <td>{{ table.sum_real }}</td>
              </tr>
        </b-table>
    </div>
    </template>
    <script>
    import Vue from 'vue'
    const axios = require('axios')
    window.onLoad = function () {
      var app = new Vue({
        el: '#tabla_final',
        data: {
          tables: ''
        },
        methods: {
          allRecords: function () {
            axios.get('http://localhost/Tribeca/api.php')
              .then(function (response) {
                app.tablas = response.data
                console.log(response.data)
              })
              .catch(function (error) {
                console.log(error)
              })
          }
        }
      })
    }
    </script>

标签: node.jsvue.jsaxios

解决方案


如果您使用的是单文件 Vue 组件,这意味着vue-loader希望<template>标签的内容是组件的模板定义,并且<script>标签的内容要导出实例化 Vue 实例时使用的配置对象。

目前,您<template>包含有效的模板定义,但您<script>不导出任何内容。因此,当 Vue 实例根据该文件的内容被实例化时,它不知道在哪里可以找到tables模板中引用的属性。

您似乎正在尝试将 Vue 实例安装到模板定义中的元素。但是,您应该只导出您的 Vue 实例配置对象:

<template>
  <div >
    <input type='button' @click='allRecords()' value='Select All users'>
    <b-table striped hover responsive id="tabla_final" >
      <tr v-for='table in tables'>
        <td>{{ table.sum_real }}</td>
        <td>{{ table.sum_ppto }}</td>
        <td>{{ table.sum_real }}</td>
      </tr>
    </b-table>
  </div>
</template>

<script>
import Vue from 'vue'
const axios = require('axios')

export default {
  data() {
    return { tables: '' }
  },
  methods: {
    allRecords: function () {
      let self = this;
      axios.get('http://localhost/Tribeca/api.php')
        .then(function (response) {
          self.tables = response.data
          console.log(response.data)
        })
        .catch(function (error) {
          console.log(error)
        })
      }
    }
  })
}
</script>

请注意,您还需要创建data一个返回对象的函数,并在调用的回调中正确引用tablesdata 属性。thenaxios


推荐阅读