【问题标题】:Data not refreshing from child component to parent数据未从子组件刷新到父组件
【发布时间】:2023-03-11 00:49:01
【问题描述】:

我有一个在链接中添加的子组件。完成后,我调用父组件来获取新链接。

我在v-for 中的链接没有更新。只有当我用新条目重新加载页面时,它们才会更新。提交后,我希望我的子组件通知/调用父母 fetchLinks 函数来更新屏幕上的所有链接(它不会更新,除非我刷新页面)

这是来自 Child AddLinksComponent 的表单成功函数

// Get the new updated subscriptions 
this.$parent.fetchLinks()

父组件

<div class="card card-body" v-for="link in links" v-bind:key="link.id">
   <h2>{{ link.name }}</h2>
</div>

      <add-links></add-links>


export default {
    data() {
        return {
            links: [],
        }
    },
    components: {
       'add-links': AddLinksComponent,
    },
    methods: {
        fetchLinks() {

            fetch('/links/')
            .then(res => res.json())
            .then(res => {
                this.links = res.data
            }).catch(err => {
                console.log('Error', err)
            });
        }
    },
    created() {
        this.fetchLinks();
    },
    mounted() {

    }
}

【问题讨论】:

    标签: javascript css vue.js vuejs2 vue-component


    【解决方案1】:

    在子组件中尝试在任务完成时向父组件发出事件,例如:

     this.$emit('fetch');
    

    在父组件中:

     <add-links @fetch="fetchLinks"></add-links>
    

    【讨论】:

    • 感谢您的成功!另外,我有 'this.$set('errors', '');'然后 this.$emit 它不起作用。我必须把它放在 $set 之前,这一切都奏效了!
    • 如果我在 $set 之后设置了 $emit,它就不起作用了。我必须把 this.$emit 放在 this.$set 之前。不知道为什么,但它只能这样工作
    • 是的。我将错误设置回null。这很奇怪,但是嘿,现在一切正常:)
    猜你喜欢
    • 2019-02-17
    • 2019-11-15
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 2022-01-19
    • 2020-11-20
    • 2017-10-01
    相关资源
    最近更新 更多