Home > Software design >  Change value of variable in Nuxt 3 with vue.js
Change value of variable in Nuxt 3 with vue.js

Time:12-02

Im really new to Nuxt 3 and Vue 3. I just want simple value change when i click on my div tag.

<a id="change" @click="changeValue()">{{value}}</a>
<script  lang="ts" setup>
let value = "Old";
function changeValue(){
  value="new"
}
</script>

This is the only thing i tried

CodePudding user response:

To change the value when you click on a div tag, you can use a method in your component's script section and bind it to the @click event on the div tag.

Here's an example of how you can do this:

<template>
  <div id="change" @click="changeValue()">{{value}}</div>
</template>

<script>
export default {
  data() {
    return {
      value: 'initial value'
    }
  },
  methods: {
    changeValue() {
      this.value = 'new value'
    }
  }
}
</script>

In this example, the changeValue() method updates the value data property when it is called, which in turn updates the text in the div tag.

CodePudding user response:

Rap's answer is correct and that's how you do it using Options API. To add, here's another way to do it using Composition API:

  • You need to declare the value variable as a reactive variable using Ref(). Ref can hold any data type.
  • To update the reactive variable, use the .value property.
<template>
  <div id="change" @click="changeValue">{{myValue}}</div>
</template>

<script setup>
const myValue = ref("Old");
function changeValue(){
  myValue.value = "new"
}
</script>

Note: I replaced the variable name value to myValue in the example above to avoid confusion with .value property.

For further reading, you can check out the Reactivity in Vue.

  • Related