Home > Back-end >  Vuejs @input="function" is not working but @input="() => do something" is wor
Vuejs @input="function" is not working but @input="() => do something" is wor

Time:05-31

I don't understand why it is working when I am passing an anonymous function to the @input field of my html input component, but it is not working when i am calling instead a real function with the exact same code inside. Here is the code when it is not working:

<script setup>
import { ref } from 'vue'

const text = ref('')
const numberChar = ref(0)
const numberWords = ref(0)

function count() {
    numberChar = text.length
    numberWords = text.split(' ').filter((e) => e != '').length
}

</script>

<template>

<div >
<input v-model="text" placeholder="Write here" @input="count"/>
 <p>
     Text : {{text}} <br>
     Characters : {{numberChar}} <br>
     Words : {{numberWords}}
 </p>
</div>

</template>

but when I am simply putting this :

<input v-model="text" placeholder="Write here" @input="() => numberChar = text.length"/>

the numberChar value is correcttly modified and displayed. I am starting Vuejs so I am missing something but it's been an hour I am struggling with this...

CodePudding user response:

Thanks everyone, I managed to correct this issue. The problem was I wrote in my function

numberChar = text.length

instead of

numberChar.value = text.value.length

What is strange is that in my anonymous function it was working without the .value and I don't know why. In the tutorial here : https://vuejs.org/tutorial/#step-4 they are using it the way I tried to use it. And they said in the tutorial too that .value is not necessary because it is implicit if nothing is specified ?

To those of you saying the tag and title of my question were not correct, i'll try to do it better for the next time, thanks. (it is my first post on stackoverflow)

Thanks :)

CodePudding user response:

Look at: https://vuejs.org/guide/introduction.html#api-styles

What you need to do is make count visible in your component. Something like:

<script setup>
  ... 
  export default {
    methods: {
      count() {
        // Your code here.
      }
    }
  }

</script>

<template>

<div >
  <input placeholder="Write here" @input="count"/>
  ...
</div>

</template>

CodePudding user response:

I am pretty sure, if you would have press F12 and take a closer look into the console, you would see that your error occurs inside your count function. So the function itself is already called

Also you need to access your values with .value

<script setup>
import { ref } from 'vue'

const text = ref('')
const numberChar = ref(0)
const numberWords = ref(0)

function count() {
    numberChar.value = text.value.length
    numberWords.value = text.value.split(' ').filter((e) => e != '').length
}

</script>
  • Related