0

Given the following, simple 'controlled component' in Vue.js, I expected the input value to be fixed, impossible to change, since it's bound (using v-bind) by Vue:

<body>

  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

  <div id="app">

    <input type="text" v-bind:value="fixedValue">

  </div>

  <script>
    var app = new Vue({
      el: '#app',
      computed: {

        fixedValue: function () {

          return 'This should NOT change'

        }

      }
    })
  </script>


</body>

But, in reality, the input text only respects this on initial load. I can click on the input field and type anything and it WILL change. Why is that and how to prevent that?

Here's the fiddle: https://jsfiddle.net/6w74yj28/

EDIT:

To compare with React (here's the fiddle: https://jsfiddle.net/ko7duw5x/), if you create a text input and bind it's value, it's impossible to change the text input value by typing inside (which is the behavior I'm trying to achieve with Vue).

sandre89
  • 5,218
  • 2
  • 43
  • 64
  • uses [readonly property](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) like ``, in your example, you did bind the input value with the computed property=fixedValue, it is like one way traffic, if fixedValues changes, it will sync newest value to the value of the input. But if the value of the input is changed, it will not sync to fixedValue. – Sphinx Jun 01 '18 at 16:16
  • @Sphinx but that's exactly the point: I have an input that `v-on:input` emits a filtered $event.target.value removing any non digits from it. So I wanted to prevent this input field from having any non numeric values from it, but even with the 'two-way' sync it's still allowing them. – sandre89 Jun 01 '18 at 18:51
  • @Sphinx check the React fiddle for comparison. I didn't do the 'two way binding' and React's input respects the input's value to be immutable, which in my opinion is logical. – sandre89 Jun 01 '18 at 23:20
  • 1
    Vue don't really have the same 'controlled input' concept as React. The generally right way is to do this https://stackoverflow.com/questions/39782176/filter-input-text-only-accept-number-and-dot-vue-js – Jacob Goh Jun 02 '18 at 02:49

0 Answers0