Vue.js:如何传递不是父/访问Vue方法的数据? [英] Vue.js: How to pass in data that isn't a parent / access vue methods?

查看:122
本文介绍了Vue.js:如何传递不是父/访问Vue方法的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的计时器应用程序.我从服务器获取了3条数据:计时器,项目和用户.我相信我正确地遍历了计时器,但是我不确定是否应该以这种方式传递数据.我希望我的应用程序的不同部分为用户和项目使用相同的数据集,以防万一项目名称发生更改.到目前为止,这是嵌入了问题的代码.我现在想一次调用一次所有数据.

I'm working on a simple timer app. I'm getting 3 pieces of data from the server: timers, projects and users. I believe I'm looping through timers correctly, but I'm not sure if I should be passing in data this way. I want different parts of my app to use the same dataset for users and projects in case a project name changes for example. Here's the code so far with questions embedded. I would like to do a single call for now for all the data at once.

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

推荐答案

这是您应该使用

This is the standard case when you should be going for a centralised state management. As you have data which is going to be used by multiple components, If the data flow is just limited to one way: parent to child, it can be manageable, but as soon as you get the requirement of updating the parent data when child changes it, or worse, updating the sibling data when another sibling changes it, it becomes messy.

Vue提供自己的类似Flux的实现,但通常的做法是使用 vuex .这样,您可以将所有项目/用户等存储在vuex 状态中,并包含每个组件可以阅读/操作在一处初始化数据.

Vue provides it own Flux like implementation, but the general practice is to go with vuex. With this, you store all your projects/users etc in vuex state, and each component can read/update from the central state. If its changed by one component, updated version is available to all components reactively. You can initiate the data in one place using actions in vuex itself.

以下是架构图:

您可以在类似问题的此处上查看我的答案,并查看有关如何调用api的示例并将数据保存在存储区中.

You can have a look at my answer here on similar question and have a look at example on how to call api and save data in store.

这篇关于Vue.js:如何传递不是父/访问Vue方法的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆