Действия объекта в vue - PullRequest
0 голосов
/ 21 декабря 2018

У меня есть следующая структура в Vue.

App.vue

export default {
    name : "app",
    router,
    data() {
        return {
            items: {books:[], authors:[]}
        };
    },

    created: function() {
        customServiceInstance.makeAjaxCall("books.json", "get").then(res => {
            this.items.books = res.books;
            return res;
        })

        customServiceInstance.makeAjaxCall("authors.json", "get").then(res => {
            this.items.authors = res.authors;
            return res;
        })

        customServiceInstance.makeAjaxCall("genres.json", "get").then(res => {
            this.items.genres = res.genres;
            return res;
        })
    },

    methods: {

        removeEntry:function(index) {
            this.$delete(this.items.books, index);
            customServiceInstance.makeAjaxCall('books.json', 'POST', JSON.stringify(this.items.books));
        }

    },

    computed: {
        booksWithAuthor () {
            let { books, authors } = this.items

            return books.map(book => ({
                ...book,
                author: authors.find(author => author.id === book.author),
            }))
        },
    }

}
</script>
<template>
  <div id="app">
      <router-link to="/home" >Home 1</router-link>
      <router-link to="/home/2"> Home 2</router-link>
      <router-view class="view" foo="123"></router-view>
    <table class="booksTable">
        <thead>
        <tr>
            <th>Title</th>
            <th>Author</th>
            <th>Genre</th>
            <th>Image</th>
            <th>Availability</th>
            <th>Options</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(book,index) in booksWithAuthor" v-bind:key="book.name">
            <td>{{book.name}}</td>
            <td>{{book.author.name}}</td>
            <td>{{book.genre}}</td>
            <td><img class="imageBook" :src="book.imageUrl"></td>
            <td v-if="book.availability">Available</td>
            <td v-else>Unavailable</td>
            <td>
            <button class="btn add">Add</button>
            <button class="btn edit" >Edit</button>
            <button class="btn delete" v-on:click="removeEntry(index)">Delete</button>
            </td>
        </tr>
        </tbody>
    </table>
  </div>
</template>

<script>
import './styling.scss';
import customService from './components/customService';
const customServiceInstance= new customService();

import Vue from 'vue';
import VueRouter from 'vue-router';
import HomeR from './components/home.vue';
import Copil from './components/copil.vue';
Vue.use(VueRouter);


const router = new VueRouter({
  routes: [
    {path: '/home', component: HomeR},
    {path: '/home/:years', component: Copil, props:true  }
    ]
})

А это JS

export default class CustomService {
    listJson(url){
        var storageLocalData = localStorage.getItem(url);
        var obj=JSON.parse(storageLocalData);
        console.log(obj);
    };

    makeAjaxCall(url, methodType, data){
        this.listJson(url);
        var promiseObj = new Promise(function(resolve, reject){
            var storageLocalData = localStorage.getItem(url);
            if(!storageLocalData){
                var xhr = new XMLHttpRequest();
                xhr.open(methodType, url, true);
                if (data) {
                    xhr.send(data);
                } else {
                    xhr.send();
                }
                xhr.onreadystatechange = function(){
                    if (xhr.readyState === 4){
                        if (xhr.status === 200){
                            var response = xhr.responseText;
                            var respJson = JSON.parse(response);
                            localStorage.setItem(url, JSON.stringify(respJson));
                            resolve(respJson);
                        } else {
                            reject(xhr.status);
                        }
                    }
                }
            }
            else {
                resolve(JSON.parse(storageLocalData));
            }
        });
        return promiseObj;
    };
}

Я хочу создать объект Book и иметь функцию getBookById (id, list), список - это загружаемый books.json. Я хочу, чтобы эта функция возвращалаобъект книги, у которого есть имя, автор, жанр и так далее.Я много чего перепробовал, но безрезультатно.Даже пробовал в файле ts что-то вроде этого:

export default class Book {
name: String;
id: Number;
author: String;
genre: Number;
imageUrl: String;
availability: boolean;

methods: {
    getBookById:(id: Number,url: String) =>  Book {

}

}

Пожалуйста, помогите мне

1 Ответ

0 голосов
/ 21 декабря 2018

Я хочу создать объект Book и иметь функцию getBookById (id, list), список - это загружаемый books.json. Я хочу, чтобы эта функция возвращала объект книги, у которого есть имя, автор, жанр

это может быть достигнуто функцией массива es6 find () .

все, что вам нужно сделать внутри вашей функции, это:

getBookById(bookId,booksList){
   return booksList.find(book=>
              book.id===bookId)
}

функция вернет первый элемент массива, который соответствует условию (book.id===bookId), или не определен, если ни один из них не соответствует.

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