我有一个Vue组件,它对Vue mixin文件进行requires
编码。所需的文件是供应商软件包的一部分,因此我无法修改该文件。我需要从mixin获取notifications
Prop 。最终结果是,我将访问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 Blade 模板的开始:
<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')]
});
最佳答案
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
}
}
});