我有一个Vue组件,requires
是一个Vue mixin的文件。所需的文件是供应商包的一部分,因此我无法修改该文件。我需要从mixin获得notifications
道具。最终结果是我将访问notifications
对象并获取读取通知量,以便将此计数显示为计算属性。似乎使用this.notifications
不起作用。我怎么能这样做?
这是我的组件:
var base = require('notifications/notifications');
Vue.component('spark-notifications', {
mixins: [base],
});
以下是上一个组件中所需的notifications
文件:
module.exports = {
props: ['notifications', 'hasUnreadAnnouncements', 'loadingNotifications'],
/**
* The component's data.
*/
data() {
return {
showingNotifications: true,
showingAnnouncements: false
}
},
methods: {
/**
* Show the user notifications.
*/
showNotifications() {
this.showingNotifications = true;
this.showingAnnouncements = false;
},
/**
* Show the product announcements.
*/
showAnnouncements() {
this.showingNotifications = false;
this.showingAnnouncements = true;
this.updateLastReadAnnouncementsTimestamp();
},
/**
* Update the last read announcements timestamp.
*/
updateLastReadAnnouncementsTimestamp() {
this.$http.put('/user/last-read-announcements-at')
.then(() => {
this.$dispatch('updateUser');
});
}
},
computed: {
/**
* Get the active notifications or announcements.
*/
activeNotifications() {
if ( ! this.notifications) {
return [];
}
if (this.showingNotifications) {
return this.notifications.notifications;
} else {
return this.notifications.announcements;
}
},
/**
* Determine if the user has any notifications.
*/
hasNotifications() {
return this.notifications && this.notifications.notifications.length > 0;
},
/**
* Determine if the user has any announcements.
*/
hasAnnouncements() {
return this.notifications && this.notifications.announcements.length > 0;
}
}
};
Laravel刀片模板的开头:
<spark-notifications
:notifications="notifications"
:has-unread-announcements="hasUnreadAnnouncements"
:loading-notifications="loadingNotifications"
inline-template>
以下是spark.js
中获取通知的方法:
data: {
user: Spark.state.user,
teams: Spark.state.teams,
currentTeam: Spark.state.currentTeam,
loadingNotifications: false,
notifications: null,
supportForm: new SparkForm({
from: '',
subject: '',
message: ''
})
},
getNotifications() {
this.loadingNotifications = true;
this.$http.get('/notifications/recent')
.then(response => {
this.notifications = response.data;
this.loadingNotifications = false;
});
},
而且,这里是一切都在一起引导app.js
:
require('spark-bootstrap');
require('./components/bootstrap');
var app = new Vue({
mixins: [require('spark')]
});
答案 0 :(得分:3)
this.notifications
是正确的方法。如果没有定义,那是因为没有notifications
道具传递给组件。
编辑:null
函数中ready()
的原因是检索通知的http请求尚未返回。 OP试图获取未读通知的数量,我们这样做了:
Vue.component('spark-notifications', {
mixins: [base],
computed: {
notificationCount:function(){
var unread = this.notifications.notifications.filter(function(notif){
return !notif.read;
});
return unread.length
}
}
});