Ошибка: Uncaught (в обещании) TypeError: невозможно создать свойство в строке

Я пытаюсь получить данные (массив с объектами) с моего сервера node js через запрос ajax и заполнить его в моем экземпляре vue.

В следующей строке я получаю сообщение об ошибке:

this.$set('tables', tables);

Сообщение об ошибке:

vue.common.js:834Uncaught (in promise) TypeError: Cannot create property '[{"name":"Test","description":"test","id":"58564cd5fdd4e76a09b1f848"},{"name":"Test","description":"test","id":"58564d04902af88009e020e8"},{"name":"test2","description":"teesten","id":"58564d68902af88009e020e9"}]' on string 'tables'

Полный код:

<template>
  <div class="container">
    <div class="row">
      <div class="col-xs-12">
        <div class="page-header">
          <h1>Database management</h1>
        </div>
        <h2>Add table</h2>
        <p class="lead">Here you can add a table.</p>
        <form method="post">
          <div class="row">
            <div class="col-xs-12">
              <div class="form-group">
                <label>Table name</label>
                <input v-model="table.name" placeholder="Table name" type="text" class="form-control">
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-xs-12">
              <div class="form-group">
                <label>Table description</label>
                <textarea v-model="table.description" placeholder="Table description" class="form-control"></textarea>
              </div>
            </div>
          </div>
          <button @click.prevent="submit" type="submit" class="btn btn-default">Add table</button>
        </form>
      </div>
    </div>

    <div class="row" v-if="tables.length > 0">
      <div class="col-xs-12">
        <h2>Interact with tables</h2>
        <p class="lead">Here you can interact with your tables.</p>
        <table class="table">
          <thead>
          <tr>
            <th>Table</th>
            <th>Interact</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="table in tables">
            <td>
              {{ table.name }}
            </td>
            <td>
              <button type="button" class="btn btn-default">Enter</button>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
  let table = {
    name: '',
    description: ''
  };

  module.exports = {
    data: function () {
      return {
        tables: [],
        table: table
      }
    },

    created: function () {
      this.getTables();
    },

    methods: {
      submit: function () {
        this.$http.post('/api/user/table', table, {
          emulateJSON: true
        }).then((response) => {
        });
      },

      getTables: function () {
        this.$http.get('/api/user/tables').then((response) => {
            console.log(JSON.stringify(response.body));
          let tables = JSON.stringify(response.body);
          this.$set('tables', tables);
        });
      }
    }

  }
</script>

person Julian    schedule 18.12.2016    source источник


Ответы (2)


Из документации здесь видно, что $set() ожидает 3 аргумента, а вы предоставляете 2, где он считает, что «таблицы» — это объект, для которого вы хотите установить свойство и значение.

https://vuejs.org/v2/api/#vm-set

Ошибка предполагает, что вы пытаетесь задать очень длинное имя свойства в строке.

rather do vue.$set(this,'tables', tables)

тогда вы будете устанавливать атрибут, называемый таблицами, для текущего объекта в таблицы массива.

person Tyrone Wilson    schedule 18.12.2016

Приведенный выше ответ также будет работать нормально.

Попробуйте присвоить значение непосредственно вашей переменной и проверить.

Пример :

this.tables = tables

Образец кода

data() : {
   return {
          participants: []
   };
},
...........
methods: {
this.$http.get('/list/participants').then((response) => {
                      console.log(response.body);
                      this.participants = response.body;
                  }, (response) => {
                      console.log('Something wrong');
                  });
 }
person Muthu17    schedule 24.01.2017