Lars Flieger
Lars Flieger

Reputation: 2554

How to set JS object as data object from VueJS?

I'm trying to set the data object with an object I'm using in my javascript code.

<div class="col-12" id="profile">
    <span>Name: @{{ name }}</span>
</div>

var userProfile = new Vue({
       el: '#profile',
       data: {
          name: user.name,
       }
    }
);

Somewhere else in my code:

user = {
   name: 'name'
};

I tried to use assign function, to set data. Doesn't work.

Anyone can give me a hint?

Upvotes: 0

Views: 31

Answers (1)

user13278024
user13278024

Reputation:

This solution works. Use the methods setName and setSurname to change the related fields. Be aware that when you update the fields in Vue's data the changes don't get reflected in the user object, which is outside the scope of Vue.

<!-- Your other code here... -->

<div id="#profile">
   <span>Name: {{ name }}</span>
   <span>Surname: {{ surname }}</span>
</div>

<script>
const user = {
   name: 'Jhon',
   surname: 'Doe'
};

new Vue({
   data () {
      return {
         name: user.name,
         surname: user.surname
      }
   },
   methods:  {
      setName (value) { this.name = value; },
      setSurname (value) { this.surname = value; }
   },
   el: '#profile'
);
</script>

Upvotes: 1

Related Questions