简体   繁体   中英

How can I change the value of a computed property?

Is there a way to change the initial data of a computed property? When I tried to change the data with an input tag, the vue gave me a warning like Write operation failed: computed property "searchField" is readonly . In case you wonder why I make this simple case with a computed rather than the data property, it is just for simplicity in the forum. There is a reason why I make it with the computed one. Here is the code.

<template>
  <input type="text" v-model="searchField" />
</template>

<script>
  export default {
    computed: {
      searchField() {
        return "";
     }
    }
  };
</script>

computed<\/strong> properties are interesting when you apply some logic around data. In your example you should first declare a data<\/strong> property, and then you can apply logic with getter \/ setter :

<template>
  <input type="text" v-model="searchField" />
</template>

<script>
  export default {
    data: () => ({
      _searchField: ''
    }),
    computed: {
      searchField: {
        get() {
          return this._searchField
        },
        set(value) {
          this._searchField = value
        }
     }
    }
  };
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM