首页 > 解决方案 > vue 中的对象动作

问题描述

我在Vue中有以下结构。

应用程序.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 {

}

}

请帮我

标签: jsonobjectvue.jsmethods

解决方案


我想创建一个对象 Book 并有一个函数 getBookById(id, list),该列表是正在加载的 books.json。我希望此函数返回具有名称、作者、流派的 book 对象

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

您在函数中要做的就是:

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

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


推荐阅读