[Vuejs]-Is there any way to access parent object?

0๐Ÿ‘

โœ…

export default {
 data: {
    a: "a",
    b: "b"
 },
 fn: {
    innerFn: () => console.log(default.data.b)
 }

}

This might do the trick for you.

0๐Ÿ‘

In your js file

// name the file as follows 
var func = ()=>{
 console.log("triggered your function"); 
}


export default {
 data: {
    a: "a",
    b: "b"
 },
 fn: {
    val: 3,
    innerFn: func
 }
}

now you can call the function

fn.innerFn();

0๐Ÿ‘

Give your object a name and then you dont have to use this to access parent property.

const obj = {
 data: {
    a: "a",
    b: "b"
 },
 fn: {
    innerFn: () => console.log(obj.data.b)
 }
}

export default obj

0๐Ÿ‘

Self referencing is what the this keyword is for.

Using Object.create you can define the objects properties in a scope, wherein the this keyword will reference the parent object.

var obj1 = Object.create(null, {
  data: {
    value: {
      a: "a",
      b: "b"
    }
  },
  fn: {
    value: function fn() {
      console.log(this.data.b);
    }
  }
});
//TEST
console.log(obj1.data.a);
obj1.fn();
//Alternative with functions
function obj2() {}
obj2.data = {
  a: "a",
  b: "b"
};
obj2.fn = function fn() {
  console.log(this.data.b);
};
console.log(obj2.data.a);
obj2.fn();

0๐Ÿ‘

You need to use the this keyword.

For Example:-

export default {
    data: {
        a: "World!"
    },
    methods: {
        consoleGreet: () => {
            console.log(`Hello, ${this.data.a}`)
        }
    }
}

Leave a comment