vue中的对象动作

时间:2018-12-21 07:39:12

标签: json object vue.js methods

我在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。我希望此函数返回具有名称,作者,类型等的book对象。 我尝试了很多事情,但没有结果。 甚至在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 :(得分:1)

  

我想创建一个对象Book并具有一个功能getBookById(id,   list),列表是正在加载的books.json,我想要这个   返回具有名称,作者,类型的书对象的函数

这可以通过es6数组函数find()来实现。

在函数内部要做的所有事情是:

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

该函数将返回与条件(book.id===bookId)相匹配的第一个数组项,如果没有匹配的项,则返回undefined。