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?
Advertisement
Answer
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>