如何更改计算属性的值?

aul*_*lah 2 javascript vue.js computed-properties

有没有办法更改计算属性的初始数据?当我尝试使用输入标签更改数据时,vue 给了我一个警告,例如Write operation failed:compute property "searchField" is readonly。如果您想知道为什么我使用计算属性而不是数据属性来制作这个简单的案例,这只是为了论坛中的简单性。我用计算出来的结果来做它是有原因的。这是代码。

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

<script>
  export default {
    computed: {
      searchField() {
        return "";
     }
    }
  };
</script>
Run Code Online (Sandbox Code Playgroud)

tec*_*hws 6

computed 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: ''
    }),
    computed: {
      searchField: {
        get() {
          return this._searchField
        },
        set(value) {
          this._searchField = value
        }
     }
    }
  };
</script>
Run Code Online (Sandbox Code Playgroud)