我想访问state
中currentUser
的{{1}}的{{1}}属性vuex
以在user.js
中使用它,但是如果我写道:auth.js
...
我收到此错误:
无法读取未定义的属性“状态”。
代码中缺少什么?
树:
store.state.currentUser.uid ===
user.js:
src
store
user
|>user.js
|>mutations.js
index.js
auth.js
auth.js:
const state = {
profile: {},
loggedIn: false,
currentUser: null,
userProfile: {}
}
export default {
namespaced: true,
state
}
index.js
import store from './store'
const fb = require('./firebaseConfig.js')
fb.auth.onAuthStateChanged(user => {
if (user) {
fb.postsCollection.orderBy('createdOn', 'desc').onSnapshot(querySnapshot => {
let createdByCurrentUser
if (querySnapshot.docs.length) {
createdByCurrentUser = store.state.currentUser.uid ===
querySnapshot.docChanges()[0].doc.data().userId ? 'Yes' : 'No'
console.log(createdByCurrentUser)
}
})
}
})
答案 0 :(得分:2)
您需要使用getters
,在doc中查看
getters.js
export default {
currentUser
}
function currentUser({ currentUser }) {
return currentUser;
}
user.js
import getters from './getters'
export default {
namespaced: true,
state: {
profile: {},
loggedIn: false,
currentUser: null,
userProfile: {}
},
getters
}
auth.js
import store from './store';
const currentUser = store.getters['user/currentUser'];
因为为模块命名空间,所以必须使用其名称作为前缀来访问getter函数