Home » vue » How to let a user modify a computed property in Vue?

How to let a user modify a computed property in Vue?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m collecting some data that I want to allow the user to download, and I’m trying to figure out the best approach for dealing with the filename. The default filename should be dynamic and based on the current date, so I figured that I need to create a computed property for it. I also want the user to have the option to change the filename. However, when I set that as the v-model on an input form, none of the changes inside the form register on the property. I can’t figure out how I can capture that new value so I can later generate the file with it. I’ve tried various combinations of v-modeland using multiple computed properties, yet none of them give me the intended result.

Here is a jsfiddle with the minimum code needed to see my issue.

Answers:

Usually you would want v-model to reference a data property rather than a computed property. That approach would look something like:

<input v-model="filename">

You could then initialize the data property with a default value

data: {
    filename: this.defaultFilename()
}

And define defaultFilename() as a method

methods: {
    defaultFilename() {
        return "whatever";
    }
}