Is it possible to use the computed properties to compute another properties in Vue?

If I have a two computed properties like this,

computed: {
  id: function(){ return this.$route.query.id; },
  hasId: function(){ return this.$route.query.id !== undefined; }
}

how can I use id to compute hasId like this pseudo-code?

computed: {
  id: function(){ return this.$route.query.id; },
  hasId: function(){ return id !== undefined; }
}

Answers:

Answer

You need to use correct scope to access a vue computed property.

as you are using just id, it will search it in global scope and not find it and will return undefined. For getting vue computed property, you need to do: this.id, so your code will look like following:

computed: {
  id: function () { return this.$route.query.id; },
  hasId: function () { return this.id !== undefined; }
}

Inside a component, this refers to our Vue instance. However you can access $route and other similar function from this, as they are defined at Vue.prototype, see below code from vue-router:

 Object.defineProperty(Vue.prototype, '$route', {
    get: function get$1 () { return this.$root._route }
 })
Answer

your pseudo code was very close. Just change id to this.id

computed: {
  id: function(){ return this.$route.query.id; },
  hasId: function(){ return this.id !== undefined; }
}
Answer

I had the same issue, and I simply resolved it using a watcher. Hope it helps:

 <div id="app">
  <label> true or false
   <input v-model="checkbox" type="checkbox">
  </label>   
</div>

<script>
new Vue({
    el: '#app',
    data: {
      checkbox: false,
    },

    computed: {

      checkboxComputed(){
        return this.checkbox;
      },

      lonelyComputed(){
        console.log('who bothers?');
        }
      },

    watch: {

      checkboxComputed(value){
        if(value){
          console.log('checkboxComputed is changed!')
          return this.lonelyComputed;
        }
      }
    }
});

</script>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.