Javascript vue原型在数据更改时不响应
我尝试创建一个自定义插件来存储数据,并将其用作全局数据。这是我的自定义插件Javascript vue原型在数据更改时不响应,javascript,vue.js,vuejs2,vue-component,Javascript,Vue.js,Vuejs2,Vue Component,我尝试创建一个自定义插件来存储数据,并将其用作全局数据。这是我的自定义插件 import {remove} from 'lodash' export const notifications = { install(Vue, options = {}) { Vue.prototype.$notifs = { count: 0, notifications: [] } Vue.pr
import {remove} from 'lodash'
export const notifications = {
install(Vue, options = {}) {
Vue.prototype.$notifs = {
count: 0,
notifications: []
}
Vue.prototype.$pushNotifs = ({content, type, timeout}) => {
Vue.prototype.$notifs.count++
Vue.prototype.$notifs.notifications.push({content, type, timeout, id: Vue.prototype.$notifs.count})
}
Vue.prototype.$removeNotifs = ({id}) => {
Vue.prototype.$notifs.notifications = remove(Vue.prototype.$notifs.notifications, (item) => item.id !== id)
}
Vue.mixin({
computed: {
$notifications() {
return this.$notifs.notifications
}
}
})
}
}
当我尝试从vue模板运行$pushNotifs方法以将某些数据推送到$notif.notifications时,模板不会更新(但其值在那里)
如何使其对模板起反应?我遵循了答案。
基本上,您创建一个类并使用一个新的Vue实例来提供反应性
plugin.js:
import Vue from 'vue';
class Notif {
constructor() {
this.VM = new Vue({
data: () => ({
notifs: [],
count: 0,
}),
});
}
get state() {
return this.VM.$data;
}
get count() {
return this.VM.$data.count;
}
}
const notif = {
Store: Notif,
install (Vue, options) {
Vue.mixin({
beforeCreate() {
this.$notif = options.store;
}
});
},
};
export default waiter;
然后使用它(在main.js中):
并访问它:
this.$notif.state.notifs.push('some notif');
在模板中:
<span>{{$notif.count}}</span>
{{$notif.count}
因此这里的
state
允许您访问所有数据,或者您可以像我在这里显示的那样公开单个项。当您像return这样检索通知时,组件中是否有计算属性。$notifs.notifications???我没有。你能举个例子吗hehe@Roliroli这很有趣吗?
this.$notif.state.notifs.push('some notif');
<span>{{$notif.count}}</span>