This question is kind of specific, but I've looked and can't find the answer here. I am working with Vue3 and trying to write a JSON and then read it. I'm not 100% sure how it works with this though. This is what I have in my js file:
class Post {
constructor(title, link, img, rank) {
this.title = title;
this.link = link;
this.img = img;
this.rank = rank;
}
}
const app = new Vue({
el: "#app",
data: {
search: "",
postList: [
new Post(
"Monke",
"test.html",
"head.png",
"Admin"
),
new Post(
"Queen",
"test.html",
"head.png",
"Admin"
),
new Post(
"Bly",
"test.html",
"head.png",
"Admin"
),
new Post(
"Blqc",
"test.html",
"head.png",
"Admin"
),
new Post(
"BlqckLight",
"test.html",
"head.png",
"Admin"
),
new Post(
"BlqckKing",
"test.html",
"head.png",
"Admin"
),
new Post(
"BlqckWTF",
"test.html",
"head.png",
"Admin"
),
new Post(
"BlqckFTW",
"test1.html",
"head.png",
"Admin"
),
new Post(
"BlqckQueen",
"test.html",
"head.png",
"Admin"
)
]
},
computed: {
filteredList() {
return this.postList.filter((post) => {
return post.title
.toLowerCase()
.includes(this.search.toLowerCase());
});
}
}
});
for (let i = 0; i < Post.length; i ) {
console.log(Post.name[i])
}
The console.log
is trying to fetch all the names but it will return like this
P
o
s
t
I know I need to now get all the names and stats to make a JSON, but making it is challenging to me, I need to return it like this
[
{
“name”: “Monke”,
“link”: “test.html”,
“img”: “head.png”,
“rank”: “Admin”
},
{
“name”: “Bly”,
“link”: “test.html”,
“img”: “head.png”,
“rank”: “Admin”
}
]
Etc. I'm sorry if this has been asked and answered before, but I simply couldn’t find it.
I then am wanting to read the JSON file which I had
JSON.parse(readFileSync(“players”).toString())
Sorry for the inconvenience if any, but I'm not very good with JSON.
CodePudding user response:
You are iterating over your class Post
, but you should be iterating over your list of Post
s. Then the log statement is outside of the Vue app, so you can't access the list. Then you are naming it title
in the class but try to access a property called name
.
I am not used to use the options API, but you could try the mounted hook within your app:
class Post {
constructor(title, link, img, rank) {
this.title = title;
this.link = link;
this.img = img;
this.rank = rank;
}
}
const app = new Vue({
el: '#app',
data: {
search: '',
postList: []
},
computed: {
filteredList() {
return this.postList.filter((post) => post.title
.toLowerCase()
.includes(this.search.toLowerCase());
});
}
},
mounted() {
this.postList = JSON.parse(readFileSync('players').toString());
this.postList.forEach((post) => console.log(post.title));
}
});