B
B
boga-net2018-06-25 11:48:04
Vue.js
boga-net, 2018-06-25 11:48:04

How in Vue in one object inside data, refer to another object in data?

Hello. Why can't I in any object in data refer to another object in the same data ?

let item4 = 'Какой-то текст';
let item5 = [1, 2, 3, 4, 5];
let item6 = {
  name: 'Trololo',
  age: '111'
};

new Vue ({
  el: '#app',
  data: {
    item1: 100,
    item2: [1, 2, 3, 4, 5],
    item3: 'Some text',
    items: [
      { name: 'Item 0', amount: 666 },
      { name: 'Item 1', amount: this.item1 }, // Пусто 
      { name: 'Item 2', amount: this.item2.length }, // TypeError: this.item2 is undefined
      { name: 'Item 3', amount: this.item3 }, // Пусто 
      { name: 'Item 4', amount: item4 },
      { name: 'Item 5', amount: item5.length },
      { name: 'Item 5', amount: item6 },
      { name: 'Item 5', amount: 'Name: ' + item6.name + ' | ' + 'Age: ' + item6.age },
    ],
  },
  methods: {
    consoleLog1() {
      console.log( this.item2.length );
    },
    consoleLog2() {
      console.log( this.item2 );
    },
  }
});

in
{ name: 'Item 1', amount: this.item1.length }
and
{ name: 'Item 2', amount: this.item2 }
can't access item1 and item2 respectively.
But in methods I can address in the same way. And I can access variables outside of the data object
and I can get the object, array or array length
Here is the HTML markup, just in case how I call the methods
<table>
    <tr v-for="item in items">
      <td>{{ item.name }}</td>
      <td>{{ item.amount }}</td>
      <td v-on:click="consoleLog1">sonsole log 1</td>
      <td v-on:click="consoleLog2">sonsole log 2</td>
    </tr>
  </table>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2018-06-25
@boga-net

you create an object, and this points to the current content. The component itself does not yet exist.
Try and see what happens if

const obj = {
  a: 1,
  b: this,
  с: this.a,
}

And what you want to assign should be done in the created hook, when $data is already defined.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question