나는 간단한 타이머 앱을 만들고있다. 타이머, 프로젝트 및 사용자 등 서버에서 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;
}
}