I need help. In my project (Vue Nuxtjs) I am fetching some random word which generate in my backend Laravel application through api response. I have to Generate random multiple word form one string value in data which I get from my axios route.
this is my data property.
data() {
return {
playWord: [],
results: [],
}
},
Response
And Axios
async fetch() {
const {
data
} = await this.$axios.get(`words/${this.$route.params.play}/play`);
this.playWord = data.word
},
I have been trying with Mounted , which give me only one random value.
mounted() {
console.log(this.$route.params.play);
var characters = 'watermelon';
var result = ""
var charactersLength = characters.length;
for (var i = 0; i < 7; i ) {
result = characters.charAt(Math.floor(Math.random() * charactersLength));
}
return this.results = result
console.log(result)
},
And method
methods: {
ply() {
var characters = 'watermelon';
var result = ""
var charactersLength = characters.length;
for (var i = 0; i < i; i ) {
result = characters.charAt(Math.floor(Math.random() * charactersLength));
}
return this.result = ply
},
},
How can I execute my required
CodePudding user response:
This will give you 30 variants (or less, depending of the random) of a single baseWord
<template>
<div>
<pre>total words: {{ result.length }}</pre>
<pre>actual list: {{ result }}</pre>
</div>
</template>
<script>
export default {
data() {
return {
baseWord: 'orange',
result: [],
}
},
mounted() {
const randomVariants = [...Array(30)].map(() =>
this.baseWord
.split('')
.sort(() => 0.5 - Math.random())
.join('')
)
const variantsWithoutInitialWord = randomVariants.filter(
(word) => word !== this.baseWord // removes 'orange' if present
)
this.result = [...new Set(variantsWithoutInitialWord)] // removing duplicates
},
}
</script>
Like this
One thing to keep in mind is to not use a random which is available on both server and client and insert it into the DOM, otherwise you will get a DOM missmatch.