VueJS 2.0从父母到孩子的沟通

时间:2017-03-23 17:47:03

标签: javascript vue.js vuejs2 vue-component

我确定有一种简单的方法可以做到这一点,但我无法弄明白。

在我的html文件中,我有以下按钮:

<button @click="showModal">Show Modal</button>

单击该按钮将运行以下方法:

new Vue({
    el: '#root',
    methods: {
        showModal() { Event.$emit('showModal'); },
    }
});

当我点击该按钮时,我想要发生的是在模态组件中切换类。以下是该组件的相关代码:

Vue.component('modal', {

    template: `
        <div :class="[ modalClass, {'is-active' : isActive }]">
            ETC...
        </div>
        `

    data() {
        return {
            isActive: false,
            modalClass: 'modal'
        }
    }

我是VueJS的新手,正在努力弄清楚如何在Vue中进行交流。我似乎无法弄清楚下一步。当单击按钮时,我该怎么做才能将isActive设置为true?

感谢您提供的任何帮助。

一切顺利,

摩西

2 个答案:

答案 0 :(得分:3)

在你的main.js中(或者你实例化你的Vue应用程序的地方)

您可以使用普通的vue实例作为eventbus

Vue.prototype.bus = new Vue();

这样你可以这样使用它:

this.bus.$on('event', (params) => {})

this.bus.$emit('event', params)

在github上查看我的一个vue项目作为一个例子,我的事件总线很多。  https://github.com/wilomgfx/vue-weather

另外在VueJS 2上看看这个免费的惊人系列,真的很棒: https://laracasts.com/series/learn-vue-2-step-by-step

使用op的问题的完整示例:

https://codepen.io/wilomgfx/pen/OpEVpz?editors=1010

答案 1 :(得分:1)

要从父母与孩子沟通,您可以使用components props

如果你有更深入的沟通(父母与少许孩子沟通),你可以使用@WilomGfx提到的busEvent。

从父母到孩子的沟通准则:

&#13;
&#13;
Vue.component('modal', {
    template: '<div :class="[ modalClass, {\'is-active\' : isActive }]">' +
            'Hello Word !' +
        '</div>',
    data() {
        return {
            modalClass: 'modal'
        }
    },
    props: {
    	isActive: { type: Boolean, default: false }
    }
});

new Vue({
    el: '#root',
    data() {
      return {
        isActive: false,
      }
  },
  methods: {
    showModal() {this.isActive = true },
  }
});
&#13;
.is-active {
  color: red;
}
&#13;
<script src="https://vuejs.org/js/vue.min.js"></script>

<div id="root">
  <modal :is-active="isActive"></modal>
  <button @click="showModal">Show Modal (going red when prop isActive is true)</button>
</div>
&#13;
&#13;
&#13;

相关问题