1

I'm using Vue2 inside HTML.

Could anyone explains why isNameSet variable is undefined whereas it is set to !!name, and since name is a string (name: "yahya") and so !!name it is converted to true, so isNameSet should be true, right !?

Is it Vuejs problem, or what exactly ?!

Code :

<body>
<div id="my-id">
    <h1> Welcome {{ name }} </h1>
    <h2> {{ '!name : ' + !name }} </h2>
    <h2> {{ '!!name : ' + !!name }} </h2>
    <h2> {{ 'isNameSet: ' + isNameSet }} </h2>
    <h3 v-text="isNameSet ? 'Your name is set!' : 'Please, Set a name !' " >  </h3>
    <h3 v-text="!!name ? 'Your name is set!' : 'Please, Set a name !' " >  </h3>
</div>

<script src="vue.js"></script>
<script>
    var vm = new Vue({
        el: "#my-id",
        data: {
            name: "yahya",
            isNameSet: !!name
        },
    })
    console.log("typeof name      : ", typeof name)
    console.log("typeof isNameSet : ", typeof isNameSet)
</script>

console

Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46

2 Answers2

3

The way you are accessing it is how you would if it is a variable.

Even if you do access it like an object i.e

let obj = {
  a: "this is A",
  b: obj.a
}

it won't work.

You are currently defining what obj is. How can you get a value you are currently trying to define?

That's just like doing the following:

let a = a

You can however just initialize first and set right after

let obj = { a: "this is A" }
obj.b = obj.a

or a getter which may/may not be the right answer

let obj = {
  a: "this is A",

  get b() {
    return this.a
  }
}

That will permanently reflect value of obj.a and not just on initialization.

If you're using vue, i suggest just sticking with computed.

captainskippah
  • 1,350
  • 8
  • 16
2

data must be a function that return object:

data() {
  return {
    name: "yahay",
  }
}

and you can access data property from for example computed property:

computed: {
  isNameSet() {
    return !!this.name
  }
}
Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46
  • yes this makes sense to me. But the question still there, why is that ?! why we cannot set the value of a property based on another property of the same object ? is it because the object is not yet initialized ?! – Yahya Rechaki Sep 30 '22 at 21:00