【问题标题】:Pass information from a child component to a parent component with Vue.js使用 Vue.js 将信息从子组件传递到父组件
【发布时间】:2023-03-30 16:05:01
【问题描述】:

感谢您阅读我的问题。

我对如何在我的 Vue.js 应用程序中实现这一点存有疑问。

父组件:App.vue 子组件:Loading.vue、ProductsList.vue、NoProductList.vue

App 组件是容器。页面加载时,会显示 Loading 组件。

Loading 组件然后检查产​​品。如果有产品,Loading 组件会将产品作为对象返回。

如果没有任何产品,Loading 组件将返回 null。

如何根据 Loading 组件的返回值告诉 App 组件使用哪个组件?即.. 如果有产品,则加载 ProductsList 组件,如果没有任何产品,则加载 NoProduct 组件?。

通知父组件它应该在 Vue 中使用哪个组件的正确方法是什么?

我应该使用 $emit(将数据从子级传递给父级)、状态管理https://vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch 还是总线组件?

一些代码...

Loading.vue 组件(子):

export default {
    name: 'loading',
    data () {
        return {
            message: ''
        }
    },
    mounted: function () {
        this.loadingProcess();
    },
    methods: {
        loadingProcess: function () {
        //process
        this.$emit('found-products', 'hola');
    }
}

App.vue 组件(父级):

<template>
    <div>
        <div id="resultComponent" @found-products="checkProductsList">
            <loading></loading>
            ...
        </div>
    </div>
</template>

提前致谢。

【问题讨论】:

    标签: vue.js components


    【解决方案1】:

    对于父子交互,正确的做法是子给$emit,父设置props。

    状态管理和总线适用于更复杂的系统,其中数据必须由不密切相关的组件共享。

    【讨论】:

    • 谢谢@Roy,明白了!
    猜你喜欢
    • 2019-10-19
    • 1970-01-01
    • 2020-08-21
    • 2017-06-10
    • 2017-01-05
    • 2020-07-23
    • 2020-11-01
    • 1970-01-01
    • 2018-05-25
    相关资源
    最近更新 更多