Create a random word from a single string within the data in Nuxt.js

I am in need of assistance. In my Vue Nuxtjs project, I am fetching random words generated from my backend Laravel application through an API response. I need to generate multiple random words from a single string value in the data obtained from my Axios route.

This is my data property:

data() {
    return {
        playWord: [],
        results: []
    };
}

Here is the response and Axios call:

async fetch() {
    const { data } = await this.$axios.get(`words/${this.$route.params.play}/play`);
    this.playWord = data.word;
}

I have tried using the 'mounted' method, but it only gives me 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));
    }
    this.results = result;

    console.log(result);
}
    

And here is the method I created:

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));
        }
        this.result = ply;
    },
}

Any suggestions on how to achieve my goal?

Answer №1

Obtain 30 variations (or less, depending on randomness) 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>

Similar to the image shown here:

https://i.sstatic.net/JUxXs.png


A crucial point to remember is to avoid using the same random number generator on both server and client side when inserting it into the DOM, otherwise you may encounter a DOM mismatch.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Continuously generate new objects every second

I am working on a function that involves adding the RandomBlock object to the scene and then moving it downward on the screen. function enemyPaddleMovement() { scene.add(RandomBlock); RandomBlock.translateX(-8); } The RandomBlock object is created using ...

What steps can be taken to prevent the "unable to convert undefined to an object" error from occurring?

There seems to be an issue with some of the documents not containing the planDetails and planId properties, resulting in the error "can't convert undefined to an object." However, I need to fetch that document whether these properties exist or not. Ho ...

What benefits does using Object.create(null) offer in comparison to utilizing a Map?

I've noticed that some developers prefer using code that looks like const STUFF_MAP = Object.create(null); It seems that STUFF_MAP is intended to be used like a map, hence the choice of using Object.create(null) over {} (to avoid conflicts with prope ...

Tips for utilizing jQuery to substitute strings within a content variable?

$content = "Please locate the student results where Date of birth **IS BETWEEN** 2012-02-18 00:00:00 AND 2013-02-18 00:00:00 AND name **IS NOT EQUAL TO** 'John' AND marks **IS BETWEEN** 40 AND 75 AND grade **EQUAL TO** 'A' AND AGE **I ...

What is the best way to implement forwardRef in a distinct select component?

Currently, I am utilizing react, typescript, and styled-components to work on my project. Specifically, I am aiming to create a select component for use in React Hook Form. Initially, everything seemed to be in order, but I encountered an error from typesc ...

ajax memory leakage

Encountering a gradual memory leak issue in Internet Explorer and Firefox while utilizing a mix of ASP.NET AJAX and jQuery. The situation mirrors the one portrayed on this post: Preventing AJAX memory leaks, but with jQuery and ASP.NET AJAX instead of prot ...

Checking for the existence of a file in JavaScript

I rely heavily on the scripts and images on my website, but the problem is that everything gets saved to the cache. This means that users can't see updates unless they clear their cache or open the site in private browsing mode. I'm working on cr ...

Incorporating a closing screen into a game built with Canvas and jQuery

After following a tutorial on creating a snake game, I decided to work on enhancing it as a side project. Currently, the game has a start screen where players can begin the game by pressing "start." My goal is to implement an end screen that displays the ...

Don't delay in fulfilling and resolving a promise as soon as possible

Currently, I am facing an issue with a downstream API call that is returning a Promise object instead of resolving it immediately. This is how I am making the downstream call: const response = testClient.getSession(sessionId); When I console.log(response ...

Connecting via web sockets through SSL is not functioning properly

My Web Socket functions correctly in both the localhost and production environments (https://www.example.com). However, upon deploying the same code to the pp environment (), I encounter the error message: WebSocket handshake - Unexpected response code: 4 ...

Post-installation of NPM, configuring CA certificates on Windows system

TLDR; Is there a way to seamlessly set NODE_EXTRA_CA_CERTS in a Windows environment for NPM packages' post-install scripts without requiring system changes, configuration file modifications, or admin-level permissions? Details This issue has been f ...

How to incorporate global environmental variables into all SASS files in Nuxt.js

Is there a way to incorporate an environment variable into all my sass/scss files? This is what I have attempted in the nuxt.config.js file: export default { ... loaders: { scss: { data: '$myenv: ' + process.env.MY_ENV + ';&a ...

Removing an object from an array if it does not exist in another array: A step-by-step

Looking to remove an object from an array if it's not present in another array. After doing some research, I came across a similar question on this link, but with a different array source. Below is the example from the link: var check = [1, 2, 3]; ...

"Despite the successful execution of the PHP script, the error function in the Ajax POST request

I am working on developing a mobile app using jQuery, jQuery Mobile, and HTML with PhoneGap. I have successfully implemented AJAX to call PHP scripts on the server for tasks like updating, inserting data, and sending emails. However, I consistently encoun ...

What exactly is the purpose of the colon in JavaScript's import statement?

Looking at the following example. import { QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Lucid/Database' I am puzzled by the use of colons and I am unsure about where the imported files are being referenced from. ...

Allow users to select options after they click a radio button

I have a pair of radio buttons and two sets of select options within different classes. Upon selecting the first radio button, the select options belonging to class1 should be enabled. On the other hand, upon selecting the second radio button, the select ...

What could be the reason for react-query searching for dispatch even when redux is not activated or present in the component?

I am currently working on a component that is supposed to fetch logged-in users from the server. Despite Swagger indicating that the server code returns correctly, the component fails to make the necessary fetch request when loaded. Below is the code snip ...

Stop users from altering the model date while typing using the ui.bootstrap.datepicker-popup

I have implemented the datepicker-popup from Angular-UI Bootstrap in my application. Currently, when the user clicks and types in the text input field, $scope.dt gets updated with each keypress, causing the cursor position to reset to the end of the strin ...

How can I match dates in order to run the following code?

If Purchase Date is after 31/Mar/xxxx it should not calculate elap_yend, rem_days, depre_cur, cur_wdv. Also I have to calculate GST with some options that is if SGST and CGST are chosen, I should not calculate IGST else if IGST selected or marked it shoul ...

Remove HTML element and launch in a separate browser tab while preserving styles

I am currently working on developing a single-page application with Polymer3 (Javascript ES6 with imports). One of the key functionalities of my application involves moving widgets to new browser windows, allowing users to spread them across multiple scree ...