How can you modify the data within a Vue.js model using the model's method?

Trying to update the model with a simple action. After clicking the button, the data field "message" is changed to display "Good Bye!". However, it quickly reverts back to displaying "Hello Vue.Js!" immediately. How can you modify the value of the model within its own method?

<div id="CreateUser" class="panel panel-default">
        <div class="panel-heading">User Infos</div>
        <div class="panel-body">                
            <label> {{ message }} </label>
            <button class="btn btn-default" v-on:click="showAlert">Submit</button>                            
            @{
                <form role="form">
                    <div class="form-group">
                        @Html.TextBoxFor(m => Model.FirstName, new {id = "FirstName", @class = "form-control", placeholder = "User First Name"})
                    </div>
                    <div class="form-group">
                        @Html.TextBoxFor(m => Model.MiddleName, new {id = "MiddleName", @class = "form-control", placeholder = "User Middle Name"})
                    </div>
                    <div class="form-group">
                        @Html.TextBoxFor(m => Model.LastName, new {id = "LastName", @class = "form-control", placeholder = "User Last Name"})
                    </div>
                    <div class="form-group">
                        @Html.TextBoxFor(m => Model.Email, new {@id = "Email", @class = "form-control", @placeholder = "User Email", @type = "email"})
                        <p><b>User Email is also the login account.</b>
                        </p>
                    </div>
                    <div class="form-group">
                        @Html.TextBoxFor(m => Model.Password, new {@id = "Password", @class = "form-control", @placeholder = "User Password", @type = "password"})
                    </div>
                    <div class="form-group">                            
                        <button class="btn btn-default" v-on:click="showAlert">Submit</button>                            
                        <input type="submit" class="btn btn-info" value="Clear"/>
                    </div>
                </form>
            }
        </div>
    </div>


$(document).ready(function() {
        var app = new Vue({

            el: '#CreateUser',
            data: {
                message: 'Hello Vue.js!'
            },
            methods: {
                showAlert: function() {
                    this.message = "Good Bye!";
                }
            }
        });
    });

Answer №1

The reason for this happening is due to the form being submitted, so it needs to be prevented. One way to do this is by using the .prevent modifier on the event.

<button class="btn btn-primary" v-on:click.prevent="displayMessage">Submit</button>

Check out the demo here: http://jsfiddle.net/excujogawo/edit?html,js,output

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

Learning how to invoke a JavaScript function from a Ruby on Rails layout

In the file app/views/download.js.erb, I have defined a javascript function named timeout(). This function continuously polls a specific location on the server to check if a file is ready for download. I am currently running this function as a background ...

Mastering the use of npm and sails to create HTML-PDF files effortlessly

UPDATE: I am simplifying my question and will address any other concerns in separate posts if necessary. The initial post was too lengthy, hoping for a straightforward guide on utilizing sails to its fullest potential. Apologies. To begin with, my knowled ...

What is preventing me from running my alert script in JavaScript?

Need some assistance here. I have a simple question. I am trying to create an alert function using JavaScript, but it is not working. <script type="text/javascript"> $(".delete").click(function(){ alert("Are you sure?&q ...

Identifying flex-wrap capabilities across different browsers

Currently, I am developing a project that involves implementing a responsive grid using the flex wrap property. However, since my project needs to support IE9 and older versions of Firefox (version 28 and below), I am in need of a way to determine their ...

Issue encountered during app creation using the command line interface

After successfully installing nodejs and checking the versions of nodejs, npm, and npx, I proceeded to run the command npm install -g create-react-app which executed without any issues. However, when I attempted to create a new React app using create-react ...

Botkit corner flaw

I'm having trouble updating a dependent package included in Botkit. When I run npm install on the package.json provided below, Npm alerts me that the hoek package is vulnerable. I attempted to resolve this by running npm audit fix but it did not wor ...

Storing two values when an option is selected in a dropdown in Javascript using the map functionIn this tutorial,

The JSON data provided is structured as follows: [ { "course_name": "React", "course_id": 2 }, { "course_name": "Python", "course_id": 1 } ] Displa ...

Observable in RXJS, with a pipe that transforms based on a dynamic function

I want to create an observable that gets populated with a custom pipe every time it is called. Let me explain this concept with an example: const myObservable = timer(1000); return myObservable.pipe(getCustomPipe()); function getCustomPipe() { return c ...

AngularJS: Utilizing angular-filter for grouping by two columns

I may come across as a bit confusing, so please allow me to clarify. Note: An operational piece of code (POC) has been included with this post. I have an array of objects with 3 properties: name name team team_rank $scope.players = [ {name: & ...

Ensure that a select input, dynamically generated, is marked as 'required' only when other inputs have been filled out

Displayed below is a snapshot of a page I'm developing that allows users to input details about various rooms in a property. Users have the ability to 'add' multiple rooms, triggering javascript/jQuery to dynamically create additional input ...

Attempting to show different fields depending on the chosen option

Having an issue with the signup process for my team and competition setup. I want to implement a feature where, if the user selects 'Competition', the promo code field will be displayed. However, this field should only appear when 'Competiti ...

Code Wizard

I am currently working on a project to develop an HTML editor. How it Needs to Function Elements Inside: Text Area - Used for typing HTML as text Iframe - Displays the typed HTML as real [renders string HTML to UI] Various Buttons Functionality: When ...

Guide on connecting a D3 component to a div in a separate Vue file

Trying to integrate D3JS charts into my VueJS application has been a bit challenging. I am struggling to understand how to properly connect the D3 component to a specific div within a .vue file. While the D3 chart displays perfectly when attached to the HT ...

When using res.render to pass data to an EJS file and accessing it in plain JavaScript

I'm currently working on an Express GET function where I am sending data to an EJS file using the res.render() function. My question is, how can I access this data in plain JavaScript within the same EJS file? Here is my GET Function: router.get(&a ...

How can I retrieve a global variable in Angular that was initialized within an IIFE?

I'm a beginner in Angular, so I ask for your patience. Currently, I am in the process of migrating an app from Asp.net MVC5 to Angular. One of the key functionalities of this application involves connecting to a third-party system by downloading a Jav ...

Working with jQuery.ajax Function Calls in Array Filter Operations with Javascript

My knowledge of AJAX calls is limited, so I am unsure about how they interact with array filtering using A.filter(). The array in question is used to populate a template synchronously. // An event triggers a function to filter a list on the page. // The f ...

Notification: failed to register service worker for messaging

An issue arose during the retrieval of the token. FirebaseError: Messaging: The default service worker registration failed. Failed to register a ServiceWorker for scope http://localhost:3000/firebase-cloud-messaging-push-scopewith script http://localhost ...

Accessing and passing arguments to actions within Vuex: A how-to guide

Here is an example of one of my vuex actions. updateProds: (context, data) => { axios.get(data.url) .then((response) => { context.dispatch( ----- ); }) }, After receiving a response from the axi ...

What is the best way to transfer the value of a radio button, retrieved from a database, to a textbox?

Greetings, I am trying to figure out how to pass the value of a radio button to a textbox using jQuery and PHP. The radio buttons are generated dynamically based on rows from my database, so I set the row ID as the ID for each radio button. However, the co ...

Ways to extract innerHTML content from a loaded element generated by using the .load() method

Check out the code snippet below: template.html : <div id="nav"> Welcome to Space </div> layout.html : <div id="content"> </div> $('#content').load("template.html #nav"); ale ...