0

I am working on a web app where users can work on a project. The structure of the app is as follows:

  • Component A (app)
  • Component B1-Bn (header, footer, main window etc., children of A)
  • Component C1 (Input area; with inputs for the user to work on the project, child of main window)
  • Component C2 (Output area; canvas which shows the result based on inputs from C1. In the future also a "graphical" input area that syncs with C1. Child of main window)
  • Component D1-Dn (Single parts of the input area like tables, advanced input components etc. Child of C1)

Now the project that the user is working on consists of an object stored in Component A. Component Dn needs to write to the object in Component A and also C2 in the future.

I can't get the v-model on input components Dn to work. I tried to pass the data from A down to C1 via props / v-bind and then in Dn, I v-model the prop from C1 (which originates from A) to the input-field. I also tried to use the sync modifier without sucess.

I seem to have a lack of understanding of the vue logic. I come from a desktop background where you just define the scope of variables. I also found that other vue apprentices have the same understanding problem but somehow the answers I found where not sufficient.

I want a "global" variable that can be edited by every component and is linked to elements in the DOM. What would be the best way to achieve this?

Nathan
  • 3
  • 1
  • 2
  • You should use vuex store to have shared variables across all components.Refer the link https://vuex.vuejs.org/. – Riddhi Feb 08 '19 at 08:07

2 Answers2

1

Declare your variable at data when creating Vue Object in your root component (Component A) like

var app = new Vue({
   data: function(){
        return {
            showSetting: {}
        }
    },
})

Now you can access this showSetting variable in any component like

app.showSetting;
//change it in any component
app.showSetting = {a:1,b:2};
//or append new value to object
Object.assign({d:3},app.showSetting);
Rejoanul Alam
  • 5,435
  • 3
  • 39
  • 68
0

Thanks for the answers so far. I guess both of them work. I found another solution because now I fully understand how data is passed in vue:

Note that objects and arrays in JavaScript are passed by reference, so if the prop is an array or object, mutating the object or array itself inside the child component will affect parent state.

I will pass all data as arrays in the future, as I only want references. The only question that remains is why the programmer is not allowed to define by himself whether the data is passed by reference or not...

Source: Vue.js Guide

tony19
  • 125,647
  • 18
  • 229
  • 307
Nathan
  • 3
  • 1
  • 2