2017-06-14 75 views
1

我有孩子component并想将一些数据传递给它的父项。 我的子组件的样子:我应该在哪里放置处理程序?

// <button @click="sendClick($event)">Send</button> 
// ... 
data: function(){ 
    return { 
      mycode: "" 
     } 
    }, 
    methods: { 
     sendClick(e) 
     { 
      bus.$emit('change', this.mycode); 
     } 
} 

我父组件的样子:

var app = new Vue({ 
    el: '#app', 
    data: { 
    currentView: 'past-form', 
    mycode: '' 
    }, 
    methods: 
    { 
    changeView() 
    { 
     this.currentView = 'past-form' 
     console.log(this.mycode); 
    }, 

    }, 

    created() 
    { 
     bus.$on('change', function(mycode){ 
      this.mycode = mycode; 

     }); 
    } 

}) 
  1. 我还没有找到一个更好的地方放置bus.$onbus全局声明)比created(),但是文档声明created()适用于在页面加载后应该初始化的内容。 created()块的工作;我检查了它console.log(this.mycode),但我应该移动发射处理程序在其他地方?

  2. 这看起来像我的代码不执行mycode: '',因为console.log(this.mycode);不会打印任何东西。

+0

如果你的孩子是Vue公司的直接孩子,没有必要一辆公交车。 – Bert

回答

1

正如我在评论中提到的,如果你的组件是你的Vue的直接子,那么就不需要总线了。

也就是说,created处理程序适用于添加您的bus事件处理程序。

我希望您遇到的问题是this问题。试着改变你的处理程序

bus.$on('change', mycode => this.mycode = mycode) 

How to access the correct this inside a callback?

下面是一个例子。

console.clear() 
 

 
const bus = new Vue() 
 

 
Vue.component("child", { 
 
    template: `<button @click="sendClick($event)">Send</button>`, 
 
    data: function() { 
 
    return { 
 
     mycode: "something" 
 
    } 
 
    }, 
 
    methods: { 
 
    sendClick(e) { 
 
     bus.$emit('change', this.mycode); 
 
    } 
 
    } 
 
}) 
 

 
var app = new Vue({ 
 
    el: '#app', 
 
    data: { 
 
    currentView: 'past-form', 
 
    mycode: '' 
 
    }, 
 
    methods: { 
 
    changeView() { 
 
     this.currentView = 'past-form' 
 
     console.log(this.mycode); 
 
    }, 
 

 
    }, 
 

 
    created() { 
 
    bus.$on('change', mycode => { 
 
     this.mycode = mycode 
 
     this.changeView() 
 
    }) 
 
    } 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script> 
 
<div id="app"> 
 
    <child></child> 
 
    Parent mycode: {{mycode}} 
 
</div>

+0

谢谢,但我怎么可以改变来自child'changeView();'的调用? –

+0

@ user1432751我不知道我理解你。你想在你的事件处理程序中调用'changeView'方法吗? – Bert

+0

是的,我需要在获取数据后调用'changeView'。并显示到用户页面“我们得到了您的数据” –

相关问题