I have an array of 6 JSON objects from where I get each value to name and type in a loop. No problems with that. But I have created a variable named title and I want to change the value of that variable. The title's value is depending on the type value which I get from JSON. The values for the title should be 'SinglePost' (if type value is post), 'SinglePage' (if type value is page) or 'SingleMovie' (if type value is movies).
I want to write the values for "name" and "type" from every objects plus my title value, in 6 lines I want this: Name value - Type value - title value So for the first object it should be "Item 1 - page - SinglePage". I can get name and type from JSON but the problem is that the title variable doesn't update it's value. I get the last title value (SingleMovie) every time.
[
{
"name":"Item 1",
"href":"http://localhost/Wordpress/",
"id":"23",
"type":"page"
},
{"name":"Item 2",
"href":"http://localhost/Wordpress/item-2",
"id":"2",
"type":"page"
},
{"name":"Item 3",
"href":"http://localhost/Wordpress/item-3",
"id":"10",
"type":"page"
},
{"name":"Item 4",
"href":"http://localhost/Wordpress/item-4",
"id":"12",
"type":"page"
},
{"name":"Item 5",
"href":"http://localhost/Wordpress/item-5",
"id":"1",
"type":"post"
},
{"name":"Item 6",
"href":"http://localhost/Wordpress/item-6",
"id":"54",
"type":"movies"
}
]
<p v-for="item in newComp" :key="item.id">{{ item.name + " - " + item.type + " - " + this.title }}</p>
export default {
data() {
let title = '';
return {
posts: [],
title:'',
}
},
mounted() {
fetch('http://localhost/Wordpress/wp-json/wp/v2/test')
.then(res => res.json())
.then(data => this.posts = data)
.then(err => console.log(err))
},
computed: {
newComp() {
const posts = this.posts;
if(posts.filter(item => item.type === 'post'))
{
this.title = 'SinglePost';
}
if(posts.filter(item => item.type === 'page'))
{
this.title = 'SinglePage';
}
if(posts.filter(item => item.type === 'movies'))
{
this.title = 'SingleMovie';
}
return posts
}
},
}
The reason why you're getting 'SingleMovie'
every time is that all of the filter
loops will modify the title. But the last loop will win because it is the last one to change the value of this.title
.
Instead you can look up the title for each item in your array and add that title to the item. The example below loops over each item and adds a title
property.
export default {
data() {
return {
posts: []
}
},
mounted() {
fetch('http://localhost/Wordpress/wp-json/wp/v2/test')
.then(res => res.json())
.then(data => this.posts = data)
.catch(err => console.log(err))
},
computed: {
newComp() {
const posts = this.posts;
const titleMap = {
post: 'SinglePost',
page: 'SinglePage',
movies: 'SingleMovie'
};
return posts.map(item => ({
...item,
title: titleMap[item.type]
}));
}
}
}
Instead of using the title
from the state, use the item.title
property.
<p v-for="item in newComp" :key="item.id">{{ item.name + " - " + item.type + " - " + item.title }}</p>