2

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> 
1

1 Answer 1

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> 
Sign up to request clarification or add additional context in comments.

2 Comments

this is super ambiguous because you have a data and a computed property with the same name, and the computed is useless here because it just return the data
@FlorentBouisset You are right, it is ambiguous, but he also explains why computed values should be used only when you apply logic or compute (calculate) a new value based on your data state, OP should use a data property instead of a computed property if he is not going to make any change to it besides getting the value as it is or setting the value of "searchField" without any further changes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.