如何解决从父组件向子组件传递数据时,有没有办法检查 props 的状态
我被一个问题困扰了很久。现在我正在使用 Vue.js 开发一个 web 项目。我想要做的是将数据从父组件传递给子组件。但是,由于异步数据传输机制,子组件的主程序只有在收到 props 数据后才会运行。所以我想知道这些是不是有一些方法可以检查子组件中props数据的状态。因此,我可以确保在数据传递后继续执行后续任务。
例如,一个可行的解决方案是 axios.requset({..}).then(res => {..})
。
解决方法
您可以在子组件中使用观察者。考虑以下父组件:
Vue.component('parent-comp',{
props: ['myProp'],template: `
<div>
<child-comp my-prop={someAsyncProp} />
</div>
`,data() {
return {
// Declare async value
someAsyncProp: null
};
},mounted() {
// Some async computation
axios
.requset({ url: '/get-data' })
.then(res => {
// Set value asynchronously
this.someAsyncProp = res;
});
}
});
您的子组件将使用观察者检查数据是否可用:
Vue.component('child-comp',template: '<div></div>',watch: {
// Watch the property myProp
myProp(newValue,oldValue) {
if (newValue !== null) {
// Do something with the props that are set asynchronously by parent
}
}
}
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。