Tips on accessing InnerText with VUEJS

I'm struggling with displaying the innerText generated by my generatePseudonym() function in a modal dialog. To better illustrate, here is a screenshot of what I mean: https://i.sstatic.net/pEl5P.png I am aiming to show the output Anastasia Shah as the Hello String when I click the generate pseudonym button. I have attempted using the mustache syntax {{ logPseudonym() }}, but unfortunately, it is not producing the desired outcome. Below is my code:

<v-dialog transition="dialog-top-transition" max-width="600">
        <template v-slot:activator="{ on, attrs }">
            <v-btn
                @click="logPseudonym()"
                width="220"
                color="#80B923"
                class="white--text"
                v-bind="attrs"
                v-on="on"
                >Generate Pseudonym</v-btn
            >
        </template>
        <template v-slot:default="dialog">
            <v-card>
                <v-toolbar color="#80B923" dark>Your Pseudonym</v-toolbar>
                <v-card-text>

                    //text should be ender in here
                    <span class="text-h3 pa-12">
                        {{ logPseudonym() }}
                    </span>
                    //text should be render in here

                </v-card-text>
                <v-card-actions class="justify-end">
                    <v-btn text @click="dialog.value = false">Close</v-btn>
                </v-card-actions>
            </v-card>
        </template>
    </v-dialog>
export default {
    methods: {
        //fetching the data from API
        async getAPIData(url) {
            try {
                const res = await fetch(url);
                if (!res.ok) {
                    throw new Error("The network is not connected");
                }
                return res.json();
            } catch (err) {
                console.error("Failed to fetch the data:", err);
            }
        },
        //
        getAPINames(genderType) {
            return this.getAPIData(
                `https://localhost:3000/data/names-${genderType}.json`
            );
        },
        randomNameGenerator(names) {
            return names[Math.floor(Math.random() * names.length)];
        },
        async generatePseudonym(gender) {
            try {
                const res = await Promise.all([
                    this.getAPINames(
                        gender || this.randomNameGenerator(["male", "female"])
                    ),
                    this.getAPINames("surnames")
                ]);

                const [firstNames, lastNames] = res;

                const firstName = this.randomNameGenerator(firstNames.data);
                const lastName = this.randomNameGenerator(lastNames.data);

                return `${firstName} ${lastName}`;
            } catch (error) {
                console.error("Unable to generate name:", error);
            }
        },
        logPseudonym(gender) {
            this.generatePseudonym(gender).then(console.log);
        }
    }
};
</script>

Answer №1

Make sure to define a data variable called logPseudonym, set this variable within the logPseudonym() function, and then access it using mustache syntax like {{this.logPseudonym}}.

If you directly use a function within mustache, a new name will be generated after rendering which can cause the click event to not work properly.

data() {
    return {
         logPseudonym: ""
    }
}

logPseudonym(gender) {
    this.generatePseudonym(gender).then((val) => { this.logPseudonym = val;});
}

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

The command `sequelize.sync({force:true}) is running into issues and the log output is coming up empty

I encountered a multitude of questions while working on this particular issue. None of them seemed to have the same problem, and after 20 straight hours of trying to solve it, I'm feeling quite stressed. So, I apologize if I missed a similar issue. Th ...

What causes fs to produce an error when routing to a new page, yet refreshing the page resolves the issue?

Concern: I have developed a NextJs application with 4 input fields, each connected to a predefined options list read in as a json file within the project. The user can select two fields and then proceed to a search page by clicking a button. From the sear ...

Utilize a traditional JavaScript class to instantiate an object in Vue.js

Is it possible to integrate a standard JavaScript class into a Vue.js component without needing anything static? If not, I am open to switching to React or Angular. Are they more suitable than Vue.js for code reusability? Test.js file: class Test { co ...

I am facing difficulty in incorporating an IP address or URL within an IFRAME in my Cordova Android application

This page does not allow any iframes to load except for the YouTube video URL. When attempting to use any other iframe URL, the following error code is displayed: Error : net::ERR_BLOCKED_BY_RESPONSE In the example below, any URL or IP address fails to l ...

tips for formatting code to prevent warnings in Vue

Currently tackling my inaugural Vue project at the workplace, I've encountered warnings that need to be resolved by utilizing --fix. These warnings mainly pertain to indentation, spacing, new lines, and similar issues. Is there a specific formatter de ...

Incorporate numerous loading elements into Nuxt for enhanced user experience

Is there a way to incorporate multiple loading components in Nuxt and assign them unique names like: for guest users this.$nuxt.$loading.guestLoader.start() for private users this.$nuxt.$loading.privateLoader.start() For documentation, check: https://nux ...

Server experiencing slow performance with Node.js formidable file uploads

When sending files as form data along with some fields using an http post request in angular.js and receiving file in app.post in node.js, the performance is inconsistent. While local testing shows a fast upload speed of 500 mb/sec with formidable, on the ...

When using the command `nodejs fs.rm(path, { recursive: true, force: true })`, an error is thrown stating "ENOTEMPTY: directory not empty"

import { existsSync } from "fs"; import fs from "fs/promises"; export async function createDirectory(path: string) { if (existsSync(path)) { try { await fs.rm(path, { recursive: true, force: true }); } catch (e) { console.log("ERR ...

Tips for transferring form data from a React frontend to the backend Node.js server

I have been attempting to send FormData from React JS to my backend (Express Node server) with the code snippet provided below. However, I am encountering an issue where req.body.myFormData in expressTest.js is showing up as empty. Despite trying various ...

At times, the Angular Modal Dropdown may unexpectedly open in an upward direction

Dealing with an AngularJS modal that contains a dropdown menu. The menu list is quite extensive. Most of the time, around 70%, the menu drops down in the lower direction which is fine. However, approximately 30% of the time, the dropdown menu appears in ...

What is the best method for displaying the accurate calculated value based on an element?

Within my "ROI calculator," there is a feature that allows users to adjust different labels. One of these labels is called "onlineRevenue." The concept is to recommend the most suitable plan based on the user's online revenue. However, I have some re ...

Chunk error ECONNREFUSED trigger

Encountered an issue while running through grunt. Getting a proxy error: Econnrefused when trying to run grunt serve. After running --verbose, it seems like the request is being blocked. I suspect it may be due to my organization's network setup, bu ...

Using Node.js for HTML redirections involves creating routes and setting

I am currently attempting to connect my Node.js API with my HTML pages. For the most part, everything is functioning correctly, but I have encountered some confusion along the way. Is there a more efficient method for redirecting an HTML page? Typically, ...

Incorporating External HTML Content Using JQuery Function

Looking for assistance with a JQuery function: function addSomeHTML() { $("#mysection").html("<div id='myid'>some content here</div>"); } I am trying to have this part: <div id='myid ...

Implementing a callback function following the completion of file reading in Phonegap

I have been facing this issue for quite some time now and I need assistance in finding a solution: When it comes to developing an android app, I rely on the phonegap framework. There is an async function called readFromFile() that reads a json file store ...

Uniform Height for Several Selectors

I came across a script on Codepen created by RogerHN and decided to customize it for a project I'm currently working on: https://codepen.io/RogerHN/pen/YNrpVa The modification I made involved changing the selector: var matchHeight = function ...

Is it possible to retrieve the var name from an interpolated expression using template literals?

Suppose I have a variable like this: myVar = `Some text with ${eggs} and ${noodles} or ${pies}`; Is there a method to obtain myVar as an unprocessed string prior to variable substitution, essentially "Some text with ${eggs} and ${noodles} or ${pies}"? M ...

Manipulating webpage content with JavaScript

How can I provide visual feedback to a user while an ajax request is in progress? For example, when a user clicks a 'process' button that triggers an AJAX request to a server-side script, they should see a 'loading...' message and a gra ...

Is it possible to identify a legitimate JSONP response?

My goal is to exchange data with a web service on a separate server that lacks CORS support. I am required to utilize JSONP for this purpose. The service mandates authentication, and when the user is in an SSO environment, they are seamlessly passed throug ...

Transferring files and information using the Fetch API

I am currently working on a React application and I have defined the state of my application as shown below: const [book, setBook] = useState({ title: '', cover: {} numberPages: 0, resume: '', date: date, }); The & ...