Why Vue's controlled `<input />` without a handler can still type text into it?

Viewed 39

Please see this two minimum example of React and Vue

They all have an <input />, and bind the input value to the state.

React

import React from "react";

export default function App() {
  const [value] = React.useState("Hello World");

  return (
    <div>
      <input value={value} />
    </div>
  );
}

Vue

<template>
  <div>
    <input :value="value" />
  </div>
</template>

<script>
  export default {
    data() {
      return {
        value: "Hello World",
      };
    },
  };
</script>

If you type something into React's version input, nothing will happen.

I can understand this part because the state isn't changing, so the input value isn't changing also.

However, if you type something into Vue's version input, you can now alter the input value.

Why is this happening?

1 Answers

Vue's attribute bindings are one-way.

Vue also does not have "controlled" components.

Whenever you change the value data property, the <input> value will be updated but changing the <input> value directly won't alter the value data property.

new Vue({
  el: "#app",
  data: () => ({ value: "Hello World" })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <input :value="value" />
  <pre>value = {{ value }}</pre>
  
  <p><button @click="value = `New value ${Math.random()}`">New value</button></p>
</div>

Related