WoJ
WoJ

Reputation: 29957

How to address the data of a component from within that component?

In a standalone Vue.js script I can mix functions and Vue data:

var vm = new Vue ({
(...)
  data: {
    number: 0
  }
(...)
})

function return100 () {
  return 100
}

vm.number = return100()

I therefore have a Vue instance (vm) which data is directly addressable via vm.<a data variable>)

How does such an addressing works in a component, since no instance of Vue is explicitly instantiated?

// the component file
<template>
(...)
</template>

<script>

function return100 () {
  return 100
}

export default {
  data: function () {
    return {
      number: 0
    }
  }
}

// here I would like to set number in data to what return100() 
// will return
??? = return100()

</script>

Upvotes: 0

Views: 39

Answers (1)

choasia
choasia

Reputation: 10852

You can achieve the target by using code like this.

<template>
  <div>{{ name }}</div>
</template>

<script>
const vm = {
  data() {
    return {
       name: 'hello'
    };
  }
};

// here you can modify the vm object
(function() {
  vm.data = function() {
    return {
      name: 'world'
    };
  }
})();
  
export { vm as default };
</script>

But I really don't suggest you to modify data in this way and I think it could be considered as an anti-pattern in Vuejs.
In almost all the use cases I met, things could be done by using Vue's lifecycle. For example, I prefer to write code with the style showed below.

<template>
  <div>{{ name }}</div>
</template>

<script>
export default {
  data() {
    return {
       name: 'hello'
    };
  },
  mounted() {
    // name will be changed when this instance mounted into HTML element
    const vm = this;
    (function() {
      vm.name = 'world';
    })();
  }
};
</script>

Upvotes: 1

Related Questions