Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

vue ts项目怎样全局添加一个计算属性

比如

//main.ts
Vue.prototype.currentGroup = function() {return JSON.parse(localStorage.getItem('currentUser') as any).group}();

模板文件里使用{{currentGroup}}切换页面发现它不会更新,只执行过一次。

Vue.prototype.currentGroup = function() {return JSON.parse(localStorage.getItem('currentUser') as any).group};

{{currentGroup()}}这可以,但是要多写个()。,,不想写行么。。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你这也不叫计算属性啊,你这就是个方法、然后立即执行(即 IIFE)了啊。

计算属性好歹得是:

Object.defineProperty(Vue.prototype, 'currentGroup', {
    get() {
        return JSON.parse(localStorage.getItem('currentUser') as any).group;
    }
});

吧?

但这么做其实是有问题的,这样是脱离 Vue 生命周期的,Vue 无法检测到数据的变化。你要是不在意这个问题,倒也就将就了。

你这种场景(每个组件内都使用同一个数据源)正确的姿势应该是用 state + mixin、而不是搞什么全局计算属性。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...