[Vuejs]-In Vue.js, how can I restore data binding after changing DOM through vanilla js?

0👍

I assuming than you want put spinner image as content of your button while wait for data from your back-end, then according Vue ecosystem you could apply this logic:

  • When the button is clicked it call the method showInfo(), there
    the property isLoading is setted to true, then in the template i
    binding the attribute class using conditional assign, this mean
    if the property isLoading is true will put the css class called
    "loader"(this class have styles for spinner animation).
  • After the method fetchData() is called to simulate to fetch data
    from your back-end, when this response is finalized the property
    isLoading is setted to false, this will remove the class in
    button.
  • Same logic for the attribute "disabled".
Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',
  data: {
    text: 'user info',
    isLoading: false,
  },
  methods: {
    showInfo() {
      this.isLoading = true;
      this.fetchData()
        .then(() => {
          /* do something */
        })
        .catch(() => {
          /* handle error */
        })
        .finally(() => (this.isLoading = false));
    },
    fetchData() {
      return new Promise((resolve, reject) => {
        setTimeout(() => resolve(), 2000);
      });
    },
  },
});
button{padding:1em}.loader,.loader:after{border-radius:50%;width:5em;height:5em}.loader{font-size:10px;position:relative;text-indent:-9999em;border-top:1.1em solid rgba(255,255,255,.2);border-right:1.1em solid rgba(255,255,255,.2);border-bottom:1.1em solid rgba(255,255,255,.2);border-left:1.1em solid #fff;-webkit-transform:translateZ(0);-ms-transform:translateZ(0);transform:translateZ(0);-webkit-animation:load8 1.1s infinite linear;animation:loading 1.1s infinite linear}@-webkit-keyframes loading{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes loading{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button 
    :class="{loader: isLoading}" 
    @click="showInfo"
    :disabled="isLoading"
  >
    {{ text }}
  </button>
</div>

Leave a comment