Home > Net >  double NOT operator in Javascript Confusion (using it inside Vuejs instance)
double NOT operator in Javascript Confusion (using it inside Vuejs instance)

Time:10-01

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

CodePudding user response:

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
  }
}

CodePudding user response:

The way you are accessing it is how you would in 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.

  • Related