javascript - 从父组件到子组件的事件

标签 javascript vue.js vuejs2 vue-component

我有在父组件中生成的事件,子组件必须对其使用react。我知道这不是 vuejs2 中推荐的方法,我必须执行一个非常糟糕的 $root emit。所以我的代码是这样的。

<template>
    <search></search>
    <table class="table table-condensed table-hover table-striped" v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
        <tbody id="trans-table">
            <tr v-for="transaction in transactions" v-model="transactions">
                <td v-for="item in transaction" v-html="item"></td>
            </tr>
        </tbody>
    </table>
</template>

<script>
    import Search from './Search.vue';

    export default {
        components: {
            Search
        },
        data() {
            return { 
                transactions: [], 
                currentPosition: 0 
            }
        },
        methods: {
            loadMore() {
                this.$root.$emit('loadMore', {
                    currentPosition: this.currentPosition
                });
            }
        }
    }
</script>

如您所见,loadMore 在无限滚动时被触发,事件被发送到子组件搜索。好吧,不仅是搜索,而且因为它是根目录,所以它被广播给所有人。

对此有什么更好的方法。我知道我应该使用 Prop ,但我不确定在这种情况下我该怎么做。

最佳答案

只要有一个变量(称它为 moreLoaded),每次调用 loadMore 时它都会递增。将它和 currentPosition 作为 Prop 传递给您的 search 组件。在搜索中,您可以watch moreLoaded 并采取相应的行动。

更新
哈基? 我的解决方案?嗯,我从来没有! ;)

你也可以使用 localized event bus .像这样设置它:

export default {
    components: {
        Search
    },
    data() {
        return {
            bus: new Vue(),
            transactions: [], 
            currentPosition: 0 
        }
    },
    methods: {
        loadMore() {
            this.bus.$emit('loadMore', {
                currentPosition: this.currentPosition
            });
        }
    }
}

并将其传递给搜索:

<search :bus="bus"></search>

这将把 bus 作为 Prop (当然),并且有一个像这样的部分

created() {
    this.bus.$on('loadMore', (args) => {
        // do something with args.currentPosition
    });
}

关于javascript - 从父组件到子组件的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43256978/

相关文章:

javascript - Vue mousemove 仅在 mousedown 之后

javascript - 单击按钮开始的 SVG 路径动画

javascript - 如何检查正确加载的facebook sdk

javascript - 将 Firebase 对象转换为数组

vue.js - vuejs 从 href 标签调用方法

events - Vue 事件修饰符防止与停止

javascript - Google Maps API V3 绘图地址

vue.js - 为 Laravel sanctum 获取 401 未授权

javascript - Vue JS中通过ID获取静态JSON单品数据

api - 在 Vue 中安装时,Axios 数据不会转移到数据中