最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I change the value of a computed property? - Stack Overflow

programmeradmin5浏览0评论

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

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

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

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

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

<script>
  export default {
    puted: {
      searchField() {
        return "";
     }
    }
  };
</script>
Share Improve this question edited Sep 2, 2021 at 9:41 aulia amirullah asked Sep 2, 2021 at 3:10 aulia amirullahaulia amirullah 1961 gold badge3 silver badges12 bronze badges 1
  • 1 Use the puter setter: vuejs/v2/guide/puted.html#Computed-Setter – dRoyson Commented Sep 2, 2021 at 3:13
Add a ment  | 

1 Answer 1

Reset to default 6

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

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

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

评论列表(0)

  1. 暂无评论