javascript - 数据更改时vue原型没有反应
问题描述
我尝试创建一个自定义插件来存储数据以将其用作全局。这是我的自定义插件
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 时,模板不会更新(但它的值在那里)
...
methods: {
pushNotifs() {
this.$pushNotifs({content: 'contoh content', type: 'success', timeout: 500})
console.log(this.$notifs.notifications); // has the value
}
}
....
如何使其对模板产生反应?
解决方案
我遵循了这个答案。基本上,您创建一个类并使用一个新的 Vue 实例来提供响应性。
插件.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 中):
import notif from './plugins/plugin.js';
Vue.use(notif, {
store: new notif.Store()
});
并访问它:
this.$notif.state.notifs.push('some notif');
在模板中:
<span>{{$notif.count}}</span>
因此,您可以在此处state
访问所有数据,或者您可以像我在此处显示的那样公开单个项目。
推荐阅读
- actionscript-3 - 如何在重复我的大学项目时使 AS3 Var Loop 在 Y 轴上移动速度
- dart - Flutter:当我修改一个项目时,我的列表视图没有更新
- c# - ASP.NET Core Webservice 作为 localhost 功能,但在 IIS 中它给出了 404 Not Found 错误
- angular - RxJS 6 - Angular 7 - 正确取消来自主题的当前 http 请求
- postgresql - PostgreSQL存储过程中的递增序列
- python - 如何将表示地理编码的节点引入Graph中的边缘?
- azure-devops - 我可以拥有多个具有 MSDN 订阅的 Azure DevOps 组织吗?
- ms-access - 导入错误 7874 后尝试重命名模块找不到 module1 对象
- node.js - 在 typescript 中,promisify 将 fs.stat 转换为 ts 错误 2349
- c++ - 为什么大键集的 Get 和 MultiGet 比使用 Iterator 慢得多?