Vuejs如何在模型方法中更新模型的数据?

时间:2017-03-26 10:17:10

标签: javascript vue.js vuejs2

我正在模型中进行简单的更新。单击按钮时。它将更新数据:消息“再见!”它工作但它恢复到“你好Vue.Js!”马上。如何在自己的方法中更改模型的值?

<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!";
                }
            }
        });
    });

1 个答案:

答案 0 :(得分:1)

它发生了,因为表单已提交,因此您必须阻止它。可以在事件上使用.prevent修饰符

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

演示:http://jsbin.com/yefexanepe/edit?html,js,output