VueJS 2.0从父母到孩子的沟通 [英] VueJS 2.0 Communicating from the Parent to the Child

查看:94
本文介绍了VueJS 2.0从父母到孩子的沟通的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm sure there is a simple way to do this, but I can't figure it out.

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

In my html file I have the following button:

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

点击该按钮会运行以下方法:

Clicking that button runs the following method:

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

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

What I want to happen when I click on that button is to toggle a class in a modal component. Here is the relevant code for the component:

Vue.component('modal', {

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

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

我是VueJS的新手,我正试图弄清楚如何在Vue中进行交流。我似乎无法想象下一步。当点击按钮时,我必须做什么才能将isActive设置为true?

I am new to VueJS and am trying to figure out how to communicate in Vue. I can't seem to figure out the next step. What do I have to do so that isActive is set to true when the button is clicked?

感谢您提供任何帮助。

一切顺利,

Moshe

推荐答案

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

In your main.js (or where ever you instantiate your Vue app)

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

You can use a plain vue instance as an eventbus

Vue.prototype.bus = new Vue();

这样你可以这样使用它:

this way you can use it as so :

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

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

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

Check out one of my vue project on github as an example, i the eventbus a lot. https://github.com/wilomgfx/vue-weather

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

Also check out this free amazing series on VueJS 2, its really great : https://laracasts.com/series/learn-vue-2-step-by-step

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

Full blown example using the op's question:

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

这篇关于VueJS 2.0从父母到孩子的沟通的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆