D
D
danilr2019-03-15 20:01:36
Vue.js
danilr, 2019-03-15 20:01:36

How to substitute a value in input when a request is received?

When the button is clicked, an action occurs with mutations and the component opens, the problem is that if I do not use a calculated property to set the received value, then the value from vuex does not have time to load and therefore the value is not set. And if I use a computed property, then it does not allow to set an empty value in input,
this is an input handler in input.

methods: {
    handleUserName(value){
      this.userFormData.name = value
    }
  },

тут пытаюсь присваивать в маунтед(не всегда успевает за 0.5с, надо 100% вариант)
mounted() {
    setTimeout(()=>{
     if(this.user){
      this.userFormData.name = this.$store.state.administration.user.name
      } 
    },500)

так пытался получать из вычисляемого свойства(не давал менять его - все время сбрасывал)
computed: {
    userName(){
      if(this.user) return this.user.name
      else return
    }
}

here in the template like this now
<InputText
              :value="userFormData.name"
              :placeholder="'Введите имя'"
              :labelText="'Имя'"
              :type="'text'"
              @input="handleUserName($event)"
            ></InputText>

here is a request to the API that is called when the popup is called
getUsersEdit(context) {
      HTTP.post(Routes.getEditUserForm, {
        // 'id': userId
        'id': context.state.currentUserId
      })
        .then(({ data }) => {
          context.commit('getUser', data.user)
          console.log('data.user: ', data.user);
        })
        .catch(error => {
          console.error(error);
        })
    }
5c8bda343d48a212693331.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alex, 2019-03-15
@danilr

bind the input model to vuex:

<InputText
  :value="userName"
  @input="handleUserName($event)">
</InputText>

computed: {
  userName: {
    get() {
      return this.$store.state.administration.user.name
    },
    set(value) {
      this.$store.commit('setUserName', value)
    }
  }
},
methods: {
  handleUserName(value){
    this.userName = value
  }
}

in this case, after opening the popup, the name will appear immediately after the data comes from the api.
or you can open the popup only after the data comes from the api:
methods: {
  openPopup() {
    this.$store.dispatch('loadUser')
      .then(() => {
        this.popupOpen = true
      })
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question