W
W
WebDev2019-01-18 13:08:23
Vue.js
WebDev, 2019-01-18 13:08:23

How to substitute data from ajax in Vue?

There is a page with a feedback form. The user must enter their email and message. By default, you need to substitute the email address that was used during registration, but the user should be able to change it.

<form>
<input type="text" v-model="email">
<textarea v-model="message"></textarea>
</form>

To substitute the user's email, you need to wait until the request is executed (an Ajax request that stores information about the user in $store.state.user) and data about him comes.
How can I make it so that when the data arrives, it is substituted, but the user can change it?
The working version I got is this:
<script>
...
data() {
    return {
        message: '',
        email: '',
    }
},
watch {
    '$store.state.user': function() {
        this.email = this.$store.state.email;
    }
},
...
</script>

But I don't like him. Although he may be true. Tell me if it is.
I tried using computed like this:
<script>
...
data() {
    return {
        message: ''
    }
},
computed() {
    email() {
        return this.$store.state.user.email;
    }
},
...
</script>

But then, if the user manually changes this address, it will still remain the same and the value from $store will go to the server.
How to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-01-18
@kirill-93

tried to use computed <...> if the user manually changes this address, it will still remain the same

Add a setter :
email() {
  get() {
    return this.$store.state.user.email;
  },
  set(val) {
    // тут вызов мутации, которая поменяет значение в хранилище
  },
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question