Vue.js:如何传入不是父/访问vue方法的数据?

时间:2016-12-02 21:06:24

标签: ajax vue.js

我正在开发一个简单的计时器应用程序。我从服务器获取3个数据:计时器,项目和用户。我相信我正在通过计时器循环,但我不确定我是否应该以这种方式传递数据。我希望我的应用程序的不同部分在项目名称更改的情况下为用户和项目使用相同的数据集。这是迄今为止嵌入问题的代码。我想立刻为所有数据打一次电话。

<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;
        }
    }

0 个答案:

没有答案