为什么Vue EventBus在组件之间同步数据

时间:2018-09-21 03:27:32

标签: javascript laravel vue.js event-bus

我有2个组件EditModal.vue和Result.vue。我使用EventBus传输数据。如果单击“编辑”,则将显示一个模式来更改该用户的数据。但是,我的问题是:当我以模式形式更新数据时,结果数据将随之自动更改,无需单击“保存更改”。我不要。这是截图

Click edit button and show modal

Data update at to place

这是我的代码

Result.vue

    <template>
<div id="users">
    <p v-for="user in users">Member : {{ user.name }} - {{ user.age }} <button @click="editUser(user)"  class="btn btn-primary" data-toggle="modal" data-target="#edit-modal">Edit</button></p>

</div>
</template>
<script>
import {EventBus} from "./EventBus";
export default{

        data(){
            return {
                users : [
{ name : "Johnny" , age : 32} ,
{ name : "Sharon" , age : 19} ,
{ name : "Smith" , age : 22} ,
{ name : "Johnny" , age : 32} ,
{ name : "Sharon" , age : 19} ,
{ name : "Smith" , age : 22} ,
{ name : "Johnny" , age : 32} ,
{ name : "Sharon" , age : 19} ,
{ name : "Smith" , age : 22} ,
]
            }
        },
        methods : {
            editUser(user){
                EventBus.$emit('edit-user' , user)
            }
        }
    }
</script>

EditModal.vue

<template>

    <div class="modal" tabindex="-1" role="dialog" id="edit-modal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Name</p>
        <p><input class="form-control" type="text" v-model="user.name" name=""></p>
        <p>Age</p>
        <p><input class="form-control" type="text" v-model="user.age" name=""></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

</template>

<script>
    import {EventBus} from "./EventBus";
    export default{
         data(){
        return {
           user : { name : '' , age : 0 }
        }
     },
     methods : {
        showForm(user){
            this.user = user ; 
        }
     },
     created(){
        EventBus.$on('edit-user' , this.showForm);
     }
    }
</script>

如果我更改

this.user = user ; 

this.user.name = user.name ; 
this.user.age = user.age ; 

问题解决了,但是,还有更好的主意吗?

0 个答案:

没有答案