【问题标题】:VueJs Lost Prop Data After Restart Page重启页面后 VueJs 丢失道具数据
【发布时间】:2022-11-19 19:21:03
【问题描述】:

嗨朋友们,

我正在将数据从父组件传递到子组件。但是我发送给子组件的数据有时会在控制台中显示“”(空文本)。例如,当我使用 Ctrl+F5 刷新页面时。如何在不丢失数据的情况下将数据传递给子组件?你能帮助我吗?我的目标是将路由信息从父组件移动到子组件。

感谢您的帮助。

子组件代码

<script>
export default {
    props: ["currentRoute"],
    methods: {
        _checkRoutes() {
                console.log("Child Component:: ", this.currentRoute);
        }
    },
    mounted() {
        this._checkRoutes();
    }
}
</script>

父组件屏幕截图

Parent Component Parent Component set Value

Console Log

Page Route is "/"

【问题讨论】:

  • 子 mounted() 方法在父 mounted() 方法之前运行。您没有丢失 currentRoute,它只是在您控制台日志时还不可用。尝试使用vue devtools 查看实时调试数据,您应该会看到路由每次都正常传递。将来也请尽可能在您的问题中包含代码 sn-ps 而不是屏幕截图。

标签: vue.js vuejs2 parent-child vue-props


【解决方案1】:

如 cmets 部分所述,您不会丢失数据。只是您的数据(在您的情况下是道具)不是反应性的,这意味着在更新道具时,ChildComponent.vue mounted 已经被调用。

如果您希望能够处理通过道具传递的数据,您可以为该道具使用watchdocs),或者简单地定义一个取决于该特定道具的computeddocs) .

所以,在你的情况下,它应该是这样的:

export default {
    props: ["currentRoute"],
    methods: {
        _checkRoutes() {
                console.log("Child Component:: ", this.currentRoute);
        }
    },
    watch:{
        currentRoute: () {
            this._checkRoutes()
        }
    }
}

computed例子:

export default {
    props: ["currentRoute"],
    computed:{
        currentWindowRoute: () {
            // Do some checks, call a method or whatever
            // and return something (value, Boolean, whatever you need for the case)
            return this.currentRoute;
        }
    }
}

请记住,computed 方法通常需要返回值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 2017-01-04
    相关资源
    最近更新 更多