I want to get all values of a property and store it as an array. I have tried this way
data() {
return {
roomList: null
}
},
methods: {
getRooms() {
var that = this
axios.get('http://localhost:3000/roomList')
.then(function(response) {
that.roomList = response.data
})
let roomLists = that.roomList.map(i => i.name) //getting the property values
return roomLists;
},
},
mounted: function () {
this.getRooms()
},
I'm quite sure that I put the map
function in the wrong place. I have tried putting it in the data
but it doesn't work as well. I can't seem to figure out where I should put that function.
If anyone can help me, I would really appreciate it. Thank you.
CodePudding user response:
If I understood you correctly, take a look at following snippet:
new Vue({
el: "#demo",
data() {
return {
roomList: null
}
},
computed: {
roomLists() {
return this.roomList?.map(i => i.name)
}
},
methods: {
getRooms() {
axios.get('https://jsonplaceholder.typicode.com/users')
.then((response) => {
this.roomList = response.data
})
},
},
mounted() {
this.getRooms()
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.26.1/axios.min.js" integrity="sha512-bPh3uwgU5qEMipS/VOmRqynnMXGGSRv 72H/N260MQeXZIK4PG48401Bsby9Nq5P5fz7hy5UGNmC/W1Z51h2GQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="demo">
{{roomLists}}
</div>
CodePudding user response:
What I'd do here is save the full roomsList
data in your data
property and create a computed property to extract just the names that stays in-sync with the backing data.
You should also initialise roomsList
as an array
export default {
data: () => ({ roomsList: [] }),
computed: {
roomNames: ({ roomsList }) => roomsList.map(({ name }) => name)
},
methods: {
async getRooms () {
const { data } = await axios.get('http://localhost:3000/roomList');
this.roomsList = data;
}
},
mounted () {
this.getRooms()
},
};
Your template could then look something like this
<ul>
<li v-for="roomName in roomNames">{{ roomName }}</li>
</ul>