我正在研究一個簡單的計時器應用程序。我從服務器獲取3段數據:定時器,項目和用戶。我相信我正確地循環定時器,但我不確定是否應該以這種方式傳遞數據。我希望我的應用程序的不同部分爲用戶和項目使用相同的數據集,以防項目名稱更改。以下是嵌入問題的代碼。我想立刻爲所有數據做一個單獨的調用。Vue.js:如何傳遞不是父級/訪問vue方法的數據?
<script>
Vue.component('sidebar-timer', {
props: ['timer','projects','users'],
computed: {
/***** SHOULD PROJECT AND USER BE SET A DIFFERENT WAY? *****/
project: function() {
return this.projects[this.timer.project_id.toString()];
},
user: function() {
return this.users[this.timer.user_id.toString()];
}
},
template: '<li class="project-item"><div class="timer-proj-name"> @{{ project.name }}</div><div class="timer-name"> @{{ user.name }}</div> <button class="timer-start-btn">Start</button><div class="timer-duration">@{{ timer.duration }}</div><div class="timer-status">@{{ timer.status }}</div><div id="toggle-timer-notes"><div class="timer-task"> @{{ timer.notes }}</div><div>timer id: @{{ timer.id }}<input :value="timer.id"></li></div>',
})
var TimerSidebar = Vue.extend({
methods: {
updateData: function() { // GET DATA FROM THE SERVER
var self = this;
$.get('/timers/getJson', function(response){
var userObj = response.users;
var projectObj = response.projects;
var timerObj = response.timers;
var timerArr = Object.keys(timerObj).map(function (key) {return timerObj[key]; });
/***** IS THERE A WAY TO SET projects AND users AT A LEVEL OUTSIDE OF TimerSidebar? *****/
self.$set(self, 'users', userObj);
self.$set(self, 'projects', projectObj);
self.$set(self, 'timers', timerArr);
})
}
}
})
var timerSidebar = new TimerSidebar({
el: '#timer-sidebar',
data: {
timers: [],
projects: [],
users: []
},
})
methods: {
/***** HOW TO ONCLICK CALL updateTimers FROM OUTSIDE THE COMPONENT? *****/
updateTimers: function(){ // ADD TIME RECORD FROM CLICK EVENT
var newTimers = this.timers;
newTimers.push({id: 166, project_id: 123, user_id: 1});
newTimers.sort(function(timer1, timer2){
if(timer1.id > timer2.id){
return 1;
} else if(timer1.id < timer2.id){
return -1;
} else {
return 0;
}
});
this.timers = newTimers;
}
}