1

I have single file component. I need create variable like to 'data' but non reative PER component (not sharing between the same components). How can i do it in vue ?

// my-component.vue
    export default {
        data() {
            return {
                reative: 1
            };
        },
        // psevdocode 
        myNonObservableVariables(){
            return {
                simpleField: 3
            }
        },
        methods: {
            method1() {
                // can set
                this.simpleField = 5;
            }
            method2() {
               // can get
               console.log(this.simpleField);
            }
        }

Update 1: Example i create 2 components and assign random value to 'simpleField' and log to console, i need:

<my-component></<my-component> // console.log -> 555
<my-component></<my-component> // console.log -> 666

after in first component call method which assign new value = 999, after this :

<my-component></<my-component> // console.log -> 999
<my-component></<my-component> // console.log -> 666
padavan
  • 714
  • 8
  • 22
  • Does this answer your question? [How could I use const in vue template?](https://stackoverflow.com/questions/42662144/how-could-i-use-const-in-vue-template) – Terry Jan 31 '21 at 17:26
  • @Terry if use data:{ CREATE_ACTION: CREATE_ACTION } will be share between components – padavan Jan 31 '21 at 17:34
  • I feel like you are not understanding correctly how the component are instanciated. Could you please add information on how you declare your components ? – Nicolas Jan 31 '21 at 17:40
  • @Nicolas add Update 1 – padavan Jan 31 '21 at 17:47

1 Answers1

1

You can define a custom map of such variables in this on created as follows:

const childcomponent = Vue.component('childcomponent', {
  template: '#childcomponent',
  props: ['id'],
  created() { this.myNonObservableVariables = { simpleField: 3 } },
  mounted() {
    let simpleField = this.getNonObservableVariable('simpleField');
    console.log('Before: simpleField', simpleField);
    this.setNonObservableVariable('simpleField', this.id);
    simpleField = this.getNonObservableVariable('simpleField');
    console.log('After: simpleField', simpleField);
  },
  methods: {
    setNonObservableVariable(key, value) {
      this.myNonObservableVariables[key] = value; 
    },
    getNonObservableVariable(key) { 
      return this.myNonObservableVariables[key]; 
    }
  }
});

new Vue({
  el:"#app",
  components: { childcomponent },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<template id="childcomponent"><div><div></template>

<div id="app">
  <div><childcomponent :id="1"/></div>
  <div><childcomponent :id="2"/></div>
</div>
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48