当它解决了 Vue firebase 时传递道具
Pass down prop when it has resolved Vue firebase
我有一个问题,我想将 firebase 用户作为 prop 从根组件向下传递到我的子组件。我通过将用户传递到我的路由器成功完成了这一步。
但是,问题是我将新的 Vue 实例包装在 onAuthStateChange 侦听器中。
const unsubscribe = auth.onAuthStateChanged(user => {
new Vue({
router,
el: '#app',
template: '<App :user="user" />',
components: { App },
data() {
return {
user: {
email: user.email,
uid: user.uid,
capital: findUserById(user.uid),
},
};
},
});
//remove this listener so that we aren't trying to make new vue objects
//every time the auth state changes.
unsubscribe();
});
按预期按 ID 查找用户 returns 用户。然而,它在 Vue 组件创建后 运行 导致 capital 未定义。
const findUserById = id => {
db
.ref()
.child('users/')
.orderByChild('uid')
.equalTo(id)
.once('value', function(snap) {
const obj = snap.val();
return obj[Object.keys(obj)[0]].capital;
});
};
有什么解决办法吗?我尝试在 mounted 生命周期中更新道具,仍然没有运气。
我的应用程序组件只是一个 Vue 路由器
我通过在辅助函数中返回一个 promise 解决了这个问题
export function findUserById(id) {
return new Promise((resolve, reject) => {
db
.ref()
.child('users/')
.orderByChild('uid')
.equalTo(id)
.on('value', snap => {
const obj = snap.val();
resolve(obj[Object.keys(obj)[0]]);
});
});
}
并且由于 Vue 可以在您使用计算属性时对更改做出反应,所以我用它来等待辅助函数返回承诺的结果。
然而,这样做并不是那么愉快,所以我使用了一个特别适合这类事情的辅助 Vue 库 - https://github.com/foxbenjaminfox/vue-async-computed
然后我可以做这样的事情:
asyncComputed: {
async user() {
return await findUserById(user.uid);
},
},
我有一个问题,我想将 firebase 用户作为 prop 从根组件向下传递到我的子组件。我通过将用户传递到我的路由器成功完成了这一步。 但是,问题是我将新的 Vue 实例包装在 onAuthStateChange 侦听器中。
const unsubscribe = auth.onAuthStateChanged(user => {
new Vue({
router,
el: '#app',
template: '<App :user="user" />',
components: { App },
data() {
return {
user: {
email: user.email,
uid: user.uid,
capital: findUserById(user.uid),
},
};
},
});
//remove this listener so that we aren't trying to make new vue objects
//every time the auth state changes.
unsubscribe();
});
按预期按 ID 查找用户 returns 用户。然而,它在 Vue 组件创建后 运行 导致 capital 未定义。
const findUserById = id => {
db
.ref()
.child('users/')
.orderByChild('uid')
.equalTo(id)
.once('value', function(snap) {
const obj = snap.val();
return obj[Object.keys(obj)[0]].capital;
});
};
有什么解决办法吗?我尝试在 mounted 生命周期中更新道具,仍然没有运气。
我的应用程序组件只是一个 Vue 路由器
我通过在辅助函数中返回一个 promise 解决了这个问题
export function findUserById(id) {
return new Promise((resolve, reject) => {
db
.ref()
.child('users/')
.orderByChild('uid')
.equalTo(id)
.on('value', snap => {
const obj = snap.val();
resolve(obj[Object.keys(obj)[0]]);
});
});
}
并且由于 Vue 可以在您使用计算属性时对更改做出反应,所以我用它来等待辅助函数返回承诺的结果。 然而,这样做并不是那么愉快,所以我使用了一个特别适合这类事情的辅助 Vue 库 - https://github.com/foxbenjaminfox/vue-async-computed 然后我可以做这样的事情:
asyncComputed: {
async user() {
return await findUserById(user.uid);
},
},