0

I need to show the status of an object if it has a property or not. I add a property id to object and console.log shows it is true, But it is not updated in DOM element. How can I see the status in DOM element?

var app = new Vue({
  el: '#app',
  data() {
    return {
      children: {}
    }
  },
  methods: {
    fillChildren() {
      this.children['id'] = 'child1Id'
      console.log(this.children.hasOwnProperty('id')) // This is true
    }
  }
})
<link type="text/css" rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/[email protected]/dist/bootstrap-vue.css" />

<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-vue.min.js"></script>


<div id="app">
  <div @click="fillChildren">Fill children</div>
  {{children.hasOwnProperty('id')}} <!-- I want to see true after click -->
</div>

1 Answer 1

1

From Reactivity in Depth:

Vue cannot detect property addition or deletion.

You can circumvent this limitation by using the vm.$set instance method:

var app = new Vue({
  el: '#app',
  data() {
    return {
      children: {}
    }
  },
  methods: {
    fillChildren() {
      this.$set(this.children, 'id', 'child1Id')
      console.log(this.children.hasOwnProperty('id')) // This is true
    }
  }
})
<link type="text/css" rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/[email protected]/dist/bootstrap-vue.css" />

<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-vue.min.js"></script>


<div id="app">
  <div @click="fillChildren">Fill children</div>
  {{children.hasOwnProperty('id')}} <!-- I want to see true after click -->
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.