Как получить длину массива для динамического массива - PullRequest
1 голос
/ 05 ноября 2019

у вас есть идея, как получить массив строк с числами после загрузки всех данных из API. Мне нужно установить totalRows для таблицы разбивки на страницы, но

this.questions = this.questions.lenght

не работает и возвращает ноль.

export default {
    data() {
        return {
            questions: [],
            fields: [
                { key: 'id', label: 'ID', sortable: true },
                { key: 'title', label: 'Title', sortable: true },
                { key: 'updated_at', label: 'Last update', sortable: true},
            ],
            totalRows: 13,
            currentPage: 1,
            perPage: 5,
            pageOptions: [5, 10, 15]
        }
    },
    components: {},
    created() {
        axios.get('/api/question')
        .then(res => this.questions = res.data.data)
        .catch(error => console.log(error.response.data))
    },
}

Я дополнительно добавляю то, что возвращает мой API

questions:Array[10]
--0:Object
-----body:"Sed minima nemo fuga libero. Rerum incidunt odio voluptatem aut quidem consequuntur. Odio deserunt labore voluptatem quo aut atque nemo."
-----id:1
-----title:Object
-----updated_at:"1 tydzień temu"
-----user:"Ahmad Mills"

Ответы [ 2 ]

0 голосов
/ 05 ноября 2019

Вам следует рассмотреть возможность использования свойства computed. Проверьте здесь: https://vuejs.org/v2/guide/computed.html

Это будет выглядеть так:

template (пример)

<p>{{ totalRows }}</p>

<script>

export default {
    data() {
        return {
            questions: [],
            fields: [
                { key: 'id', label: 'ID', sortable: true },
                { key: 'title', label: 'Title', sortable: true },
                { key: 'updated_at', label: 'Last update', sortable: true},
            ],
            currentPage: 1,
            perPage: 5,
            pageOptions: [5, 10, 15]
        }
    },
    computed: {
        totalRows: function() {
             return this.questions.length
        },
    },
    created() {
        axios.get('/api/question')
        .then(res => this.questions = res.data.data)
        .catch(error => console.log(error.response.data))
    },
}

Второй вариант, просто поместите свойство в шаблон как:

{{ questions.length }}

Но свойство computed делает шаблон более четким и отделяет логику от визуализации (это самая ценная часть моегомнение =))

0 голосов
/ 05 ноября 2019

Помните, vue.js - это фреймворк javascript, поэтому вы можете делать все то, что умеет javascript.

Так что strings, arrays, objects и functions и т. Д. Все используютсятак же, как в javascript.

Таким образом, вы можете найти длину строки или массива как your_Array.length

 axios.get('/api/question')
    .then(
           res => {
             this.questions = res.data.data
             //now you can get length using 
             questions.length 
             //or you can create a computed property
           }
     )

Подробнее о массивах здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...