簡體   English   中英

使用 Vue.js 僅返回數組中的一些 object 字段

[英]Return only some object fields in an array using Vue.js

所以我有來自 api 請求的數組中的這些對象

(5) [{…}, {…}, {…}, {…}, {…}]
0: {ID: 1, Title: "dqdq", Description: "dqdq", IdUser: 3}
1: {ID: 2, Title: "dqdq", Description: "dqdq", IdUser: 3}
2: {ID: 3, Title: "dqdqddd", Description: "dqdq", IdUser: 3}
3: {ID: 4, Title: "dqdqddd", Description: "dqdq", IdUser: 3}
4: {ID: 5, Title: "dqdqddd", Description: "dqdq", IdUser: 3}
length: 5

我需要的是只取標題,這樣我就可以在一個 div 中循環它,等等以進行描述並將它傳遞給子組件,這樣我就可以在 html 部分中循環它

<template>
<div>
<Navbar />
<gamesIdeaList :games="games" />
</div>

</template>

<script>
// @ is an alias to /src
import Navbar from '@/components/Navbar.vue'
import gamesIdeaList from '@/components/gamesIdeaList.vue'
import axios from 'axios'
export default {
  name: 'home',
  components: {
    Navbar,
    gamesIdeaList
  },
  data() {
      return {
          games:[]
      }
  },
  //  props: info,
   mounted () {
    axios.get('http://localhost:3001/GamesIdea', {
        headers: { Authorization: `Bearer ${localStorage.usertoken}` }
      })
      .then(res => {
 this.games = res.data.data

console.log(arr)
      })
      .catch(error => {
        console.log(error)
        this.errored = true
      })
}
}
</script>

你也可以試試這個

<div>
<Navbar />
<gamesIdeaList :games="games" />
</div>

</template>

<script>
// @ is an alias to /src
import Navbar from '@/components/Navbar.vue'
import gamesIdeaList from '@/components/gamesIdeaList.vue'
import axios from 'axios'
export default {
  name: 'home',
  components: {
    Navbar,
    gamesIdeaList
  },
  data() {
      return {
          games:[]
      }
  },
  //  props: info,
   mounted () {
    axios.get('http://localhost:3001/GamesIdea', {
        headers: { Authorization: `Bearer ${localStorage.usertoken}` }
      })
      .then(res => {
 this.games = res.data.map(val => {
return {
Title: val.Title,
Description:val.Description}
})

console.log(arr)
      })
      .catch(error => {
        console.log(error)
        this.errored = true
      })
}
}
</script>```

是的,可以添加您不想要的字段作為回報

解決方案 1

this.games = res.data.data.map(({
    ID,
    IdUser,
    ...rest
}) => rest);

 var v1 = [ {ID: 1, Title: "dqdq", Description: "dqdq", IdUser: 3}, {ID: 2, Title: "dqdq", Description: "dqdq", IdUser: 3}, {ID: 3, Title: "dqdqddd", Description: "dqdq", IdUser: 3}, {ID: 4, Title: "dqdqddd", Description: "dqdq", IdUser: 3}, {ID: 5, Title: "dqdqddd", Description: "dqdq", IdUser: 3}] var games = v1.map(({ ID, IdUser, ...rest}) => rest); console.log(games);

解決方案 2

https://stackoverflow.com/a/25470077/6923146

您可以使用map

this.games = res.data.data.map(obj => {
    Title: obj.Title,
    Description: obj.Description
});

嘗試使用map陣列 function 如下:

 this.games = res.data.data.map(d=>{Title: d.Title,Description:d.Description}); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM