Using a Math function in Vue 2 framework

Asked

Viewed 39 times

0

I’m developing an api on Vue.js that has a button to calculate the power of a certain number. But when I click the button it becomes static, nothing changes. You have to make some change in the method or some configuration in Vue?

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
    <p>{{ numero }}</p>
    <button @click="potencia">Potência 2*</button>
</div>
<script>
    new Vue({
        el:'#app',
        data: {
            numero: 3
        },
        methods: {
            potencia() {
                return Math.pow(this.numero, 2)
            }
        }
    })
</script>
  • Your function returns the result of Math.pow. Where does this amount go? What would you like to do with the result?

  • The button should update the value of {{number }} inside the tag <p>. Ex: if {{number}} is 3, press the button and {{number}} is 9. Got it?

1 answer

0


Your function is returning the result. Javascript will handle this internally and will not know that what you want is to update the value of this.numero. To do this, you need to specify that you want to change the value by doing the assignment:

new Vue({
  el: '#app',
  data: {
    numero: 3
  },
  methods: {
    potencia() {
      this.numero = Math.pow(this.numero, 2)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <p>{{ numero }}</p>
  <button @click="potencia">Potência 2*</button>
</div>

  • Thank you very much. Thank you very much!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.