VueJS 2.0 从父级到子级的通信 [英] VueJS 2.0 Communicating from the Parent to the Child

查看:23
本文介绍了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?

感谢您提供的任何帮助.

Thanks for any help you can offer.

一切顺利,

莫舍

推荐答案

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

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

您可以使用普通的 vue 实例作为事件总线

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 项目为例,我经常使用 eventbus.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-循序渐进

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

使用操作问题的完整示例:

Full blown example using the op's question:

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

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

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