Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a Vue function not recognized when used in computed()?

The following code (a Vue method is used in a string template when the component is mounted) works: :

new Vue({
  el: "#app",
  methods: {
    perc: w => w / 100
  },
  mounted() {
    console.log(`hello ${this.perc(20)}`)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app"></div>

The one below = the above expanded to use this.perc() in a computed variable, fails with TypeError: this.perc is not a function

new Vue({
  el: "#app",
  methods: {
    perc: w => w / 100
  },
  computed: {
    data: {
      y: `hello ${this.perc(20)}`
    }
  },
  mounted() {
    console.log(this.data)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app"></div>

Why isn't this.perc() available in a computed variable?

like image 596
WoJ Avatar asked Oct 15 '25 03:10

WoJ


1 Answers

It must be a function in computed property.

new Vue({
  el: "#app",
  methods: {
    perc: (w) => w / 100
  },
  computed: {
    data () {
      return `hello ${this.perc(20)}`
    }
  },
  mounted() {
    console.log(this.data)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app"></div>
like image 111
d49tt0 Avatar answered Oct 17 '25 18:10

d49tt0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!