I'm writing a little quiz app using vue and tailwind, but it's my 1st time doing anything like this. I want the data to be random, so the quiz looks different each time. I am accessing my json file as follows:
<template>
<div id="app">
<ul>
<li v-for="user in users" :key="user.id">
{{user.name}}
</li>
</ul>
</div>
</template>
<script>
import usersData from "./users.json";
export default {
data() {
return {
users: usersData,
};
},
};
</script>
I was wondering if there is a quick and easy way for this to output random values from the json file. Just to be clear, I want this to still output ALL of the "names" in the json file, but in different order each time. Let me know if I'm not clear or I need to provide more info. Thanks in advance.
CodePudding user response:
You can use loadash
https://lodash.com/docs/4.17.15#shuffle
const array = [
{ some: 1 },
{ some: 2 },
{ some: 3 },
{ some: 4 },
{ some: 5 },
{ some: 6 },
{ some: 7 },
];
console.log(_.shuffle(array));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
or try it like this.
console.log( [
{ some: 1 },
{ some: 2 },
{ some: 3 },
{ some: 4 },
{ some: 5 },
{ some: 6 },
{ some: 7 },
]
.sort( () => Math.random() - 0.5) );
So make a computed property in vuejs
<template>
<div id="app">
<ul>
<li v-for="user in randomUsers" :key="user.id">
{{user.name}}
</li>
</ul>
</div>
</template>
<script>
import usersData from "./users.json";
export default {
data() {
return {
users: usersData,
};
},
computed:{
randomUsers () {
usersData.sort(() => Math.random() - 0.5))
}
}
};
</script>
CodePudding user response:
To do this, we use the following method
Html/Vue Code
<template>
<div id="app">
<ul>
<li v-for="user in users" :key="user.id">
{{user.name}}
</li>
</ul>
</div>
</template>
JavaScript Code
<script>
import usersData from "./users.json";
export default {
data() {
return {
users: usersData,
};
},
computed:{
random(p) {
//try this shuffle function
for (
var j, x, i = p.length;
i;
j = Math.floor(Math.random() * i), x = p[--i], p[i] = p[j], p[j] = x
);
return p;
}
}
,
created(){
this.users=random(users)
}
};
</script>