2016-10-28 33 views
1

我对Vue.js非常陌生,并且使用v6-class-component的es6语法。我在尝试从孩子向父母发送活动时遇到问题。我遵循默认Vue.js语法的逻辑,但无法完成。这里有一些更多的信息:

export default class HorizontalNavigation { 

    handleClick (e) { 
    e.preventDefault(); 
    // console.log(e.target.dataset.section); 
    this.$emit('ChangeView', e.target.dataset.section); 
    } 

    render (h) { 
    return (
     <div class={ style.horizontalNavigation } > 
     <div class='sections-wrapper'> 
      <div class={ style.sections }> 
      <ol> 
       <li><a on-click={ this.handleClick } href='#1' data-section='1' class='selected'>We are</a></li> 
       <li><a on-click={ this.handleClick } href='#2' data-section='2'>Services</a></li> 
       <li><a on-click={ this.handleClick } href='#3' data-section='3'>Cases</a></li> 
       <li><a on-click={ this.handleClick } href='#4' data-section='4'>Studio</a></li> 
       <li><a on-click={ this.handleClick } href='#5' data-section='5'>Career</a></li> 
       <li><a on-click={ this.handleClick } href='#6' data-section='6'>Contact</a></li> 
      </ol> 

      <span class='filling-line' aria-hidden='true'></span> 
      </div> 
     </div> 
     </div> 
    ); 
    } 
} 

这是孩子。我在每个li上附加一个点击,将它传递给父项。这是父母。

export default class ViewsContainer { 

    ChangeView (data) { 
    console.log(data); 
    } 

    render (h) { 
     return (
      <div class={ style.restrictOverflow } > 
      <HorizontalNavigation /> 
      <main class={ style.viewsContainer } on-ChangeView={ this.ChangeView  } > 
       <SingleView dataSection='weare' id='1' class='selected' /> 
       <SingleView dataSection='services' id='2' /> 
       <SingleView dataSection='cases' id='3' /> 
       <SingleView dataSection='studio' id='4' /> 
       <SingleView dataSection='career' id='5' /> 
       <SingleView dataSection='contact' id='6' /> 
      </main> 
      </div> 
     ); 
     } 
    } 

继vue.js语法,我应该能够听从父儿童的事件由事件传递给元素就像一个@ChangeView但什么也没有通过组件,但道具旅行... 有什么关于这个的?谢谢 !

回答

12

您需要$emit您要接收您的$emit视图模型,请使用bus或使用https://vuex.vuejs.org/en/intro.html

最简单的方法,就是简单地$直接排放到父:

this.$parent.$emit('ChangeView', e.target.dataset.section); 

这是正常的,但如果你有你需要的$emit每个$parent链组件的长链。

另一种方法是通过将公交车在你的主要成分,为emiting VM Vue使用作为总线到它:

var bus = new Vue({}); 
var vm = new Vue({ 
    methods: { 
    changeView() { 
     bus.$emit('ChangeView', e.target.dataset.section); 
    } 
    } 
); 

也可以发射到$root,但不建议这样做。但是,如果您的app确实变得相当复杂,您可能需要考虑使用Vues自己的状态管理系统vuex

可以使用$on并侦听特定事件监听在视图模型的$emit

var vm = new Vue({ 
    created() { 
    this.$on('ChangeView', section => { 
     console.log(section); 
     }); 
    } 
); 

这也将是类似的是你正在使用的公交车,但你刚才提到的公交车改为:

bus.$on('ChangeView, ...) 

而且你也可以直接在你的HTML中使用`v型上使用它:

<div v-on:ChangeView="doSomething"></div> 
+0

谢谢克雷格!但是,你怎么听父母,我不能得到任何东西...... – Lou

+0

非常感谢Craig!我还在ChangeView侦听器上做了一个错误,而不是实例本身。所以解决我的问题是:在ViewsContainer中执行: 。 再次感谢您的时间! – Lou