Vue 2 - 组件之间的通信(发送和接收数据) [英] Vue 2 - Communication between components (sending and receiving data)

查看:29
本文介绍了Vue 2 - 组件之间的通信(发送和接收数据)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在 Vue 中开发应用程序.我在组件之间发送和接收数据时遇到问题.已经尝试过 $dispatch/$broadcast, $emit/$on 但现在仍然有效.我想将选定的 active_clubClubSelection.vue 发送到 vue_main.js.

<块引用>

Vue 版本:2.0.3

我的应用程序结构:

  1. vue_main - 主 Vue 文件

    1. HeaderElement.vue(vue_main 的子级)

      1. ClubSelection.vue(HeaderElement 的子级)

需要从 ClubSelection 发送 active_club 到 vue_main.

<块引用>

ClubSelection.vue

 <脚本>导出默认{道具: [俱乐部",头衔"],创建(){//获取俱乐部列表this.$http.get('/api/clubs', function(data) {this.clubs = 数据;控制台日志(数据);//从父级读取活动俱乐部this.selected = this.$parent.$parent.active_club;});},数据(){返回{俱乐部:[],选择:空,}},手表: {选择:功能(v){this.club = v;//发布到数据库选择的俱乐部this.$http.post('/api/clubs/' + v + '/active')},俱乐部:功能(v){this.selected = v;//在父母处更改active_club(这不起作用)//this.$emit('active_club', v);//this.$parent.active_club = v;club.$emit('active_club', v);},}}

<块引用>

vue_main.js

 const app = new Vue({路由器,数据() {返回 {用户:[],active_club:空,排名:空}},创建:函数(){var self = this;this.$http.get('/api/users/me', function(data) {this.user = 数据;self.active_club = data.active_club;})}}).$mount('#app');const club = new Vue();//这不起作用club.$on('active_club', function (id) {警报(ID)this.active_club = id;});

错误:

<块引用>

Vue 警告]:观察者club"中的错误(在组件中找到))

vue_main.js:16924 Uncaught (in promise) ReferenceError: club is not定义

我尝试了很多设置,这是其中之一.如何使其工作?

解决方案

$dispatch$broadcastVue 2.0.

就您而言,您需要的是父组件和子组件之间的通信.当子$emit发生事件时,父可以通过在模板标记本身中提供一个方法来监听它,使用v-on:parentMethod()如下:

</child-component>

上面的标记是在父组件的模板中完成的.并且父组件需要在它的 methods 中有那个 handlerMethod.

这是 Stackoverflow 上的一个示例父子通信"问题,其中还有一个 jsFiddle 示例:删除一个Vue子组件

您可以使用上述答案作为在您的应用中实现 $emit 的参考.

附加说明

我忘了提及有关您拥有的三级层次结构的说明.在您的应用中,您具有以下层次结构:

父:vue_main

子 1:HeaderElement

子 1.1:俱乐部选择

要将事件从 ClubSelection 发送到 vue_main,您可以使用 non父子通信方法,或者您可以使用中间 HeaderElement 中继事件.

以下是事件中继的工作原理:

  • 第 1 步:ClubSelection 发送一个 $emit,由 HeaderElement 使用 v-on 接收.
  • 第 2 步:HeaderElement 中的 handlerMethod 做了一个 this.$emit,它可以被你的主模板使用另一个 v-on 接收>.

虽然上述内容可能看起来有点复杂,但它比广播到应用程序中的每个组件要高效得多,因为它通常在 Angualr 1.x 或其他框架中完成.

So I working on app in Vue. I have problem with sending and receiving data between components. Already tried with $dispatch/$broadcast, $emit/$on but still now working. I want to send selected active_club from ClubSelection.vue to vue_main.js.

Vue version: 2.0.3

Structure of my app:

  1. vue_main - main Vue file

    1. HeaderElement.vue (child of vue_main)

      1. ClubSelection.vue (child of HeaderElement)

Need to send active_club from ClubSelection to vue_main.

ClubSelection.vue

    <script>

    export default{
        props: [
            'club', 'title'
        ],
        created(){

            //Get club list
            this.$http.get('/api/clubs', function(data) {
                this.clubs = data;
                console.log(data);

                //read active club from parent
                this.selected = this.$parent.$parent.active_club;
            });

        },
        data(){
            return{
                clubs: [],
                selected: null,
            }
        },
        watch: {
            selected: function(v) {
                this.club = v;

                //Post to database selected club
                this.$http.post('/api/clubs/' + v + '/active')

            },
            club: function(v) {
                this.selected = v;

                //Change active_club at parent (THIS NOT WORKING)
//              this.$emit('active_club', v);
//              this.$parent.active_club = v;
                club.$emit('active_club', v);

            },
        }

    }
</script>

vue_main.js

    const app = new Vue({
    router,
    data() {
        return {
            user: [],
            active_club: null,
            ranking: null
        }
    },
    created: function() {
        var self = this;

        this.$http.get('/api/users/me', function(data) {
            this.user = data;
            self.active_club = data.active_club;

        })

    }


}).$mount('#app');

const club = new Vue();

//THIS NOT WORKING
club.$on('active_club', function (id) {

    alert(id)
    this.active_club = id;
});

Errors:

Vue warn]: Error in watcher "club" (found in component )

vue_main.js:16924 Uncaught (in promise) ReferenceError: club is not defined

I have tried many set ups, this is one of them. How to make this working?

解决方案

$dispatch and $broadcast are deprecated in Vue 2.0.

In your case, what you need is communication between a parent component and child component. When a child $emits an event, parent can listen to it by providing a method in template markup itself, using v-on:parentMethod() as follows:

<child-component v-on:child-event="handlerMethod"></child-component>

The above markup is done inside parent component's template. And the parent component needs to have that handlerMethod in its methods.

Here is a sample "parent-child communication" question on Stackoverflow, which has a jsFiddle example also: Delete a Vue child component

You may use the above answer as reference to implement $emit in your app.

Edit: Additional Notes

I forgot to mention the note about three level hierarchy you have. In your app, you have the following hierarchy:

parent: vue_main

child 1: HeaderElement

child 1.1: ClubSelection

For sending events from ClubSelection to vue_main, you may either use non parent-child communication method or you can relay the event using the intermediate HeaderElement.

Here is how the event relay can work:

  • Step 1: ClubSelection sends a $emit, which is received by HeaderElement using v-on.
  • Step 2: The handlerMethod in HeaderElement does a this.$emit, which can be received by your main template using another v-on.

While the above may look a bit convoluted, it is much more efficient than broadcasting to every single component in the app, as it is generally done in Angualr 1.x or other frameworks.

这篇关于Vue 2 - 组件之间的通信(发送和接收数据)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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