0

Below I have an input which value I attempt to assign to a variable v. My understanding after reading similar posts is that, when the page is initialized, the value of the input is null and thus cannot be read.

<template>
  <div>
    <input type="text" id="input"/>
    {{ v }}
  </div>
</template>

<script>
export default {
  data(){
    return { v: document.getElementById("input").value }
  },
}
</script>

Two questions immediately pop up:

  • Why doesn't v: null cause an error? Would it not be equivalent to the code above?
  • What is the correct way to assign the value of the input to a variable?
1

1 Answer 1

1

Because DOM isn't available in the data function. Use mounted to access the DOM. If you want two way binding, use v-model

From docs

It is not recommended to return objects with their own stateful behavior like browser API objects and prototype properties. The returned object should ideally be a plain object that only represents the state of the component.

<template>
      <div>
        <input type="text" id="input" v-model="v" />
        {{ v }}
      </div>
    </template>

    <script>
    export default {
      data(){
        return { v: null }
      },
    }
    </script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.