Vue.js - Change element's class based on change to data property












0














I have a Vue instance which has two data properties: error which is initially set to false, and classArray which is an object that contains two classes: btn and btn-success.





btn is set to true and
btn-success is set to error, which initially is false.



I have two input elements, both of which are buttons, where the first one's class is set to classArray.



The other button, upon clicking, invokes a method attached to my Vue instance that is supposed to toggle error (so if error is true, then it becomes false, and vice versa).



My expectation is that, because btn-success in classArray is set to the value of error, that upon toggling the value of error the corresponding class should be active on my first element.



Even though the toggling of error works as expected, when inspecting the first element, it doesn't appear that the btn-success class was added.



Is there something here I'm missing, or can you not add classes to elements like this?



Also, here is the code I'm using to test this:






var app = new Vue({
el: '#app',
data: {
error: false,
classArray: {
btn: true,
'btn-success': this.error
}
},
methods: {
toggle: function() {
this.error = !this.error;
console.log(document.getElementById('input1'));
}
}
});

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<div id="app">
<input type='button' id='input1' :class='classArray' value='Submit' />
<input type='button' @click='toggle' value='Change class' />
</div>












share|improve this question



























    0














    I have a Vue instance which has two data properties: error which is initially set to false, and classArray which is an object that contains two classes: btn and btn-success.





    btn is set to true and
    btn-success is set to error, which initially is false.



    I have two input elements, both of which are buttons, where the first one's class is set to classArray.



    The other button, upon clicking, invokes a method attached to my Vue instance that is supposed to toggle error (so if error is true, then it becomes false, and vice versa).



    My expectation is that, because btn-success in classArray is set to the value of error, that upon toggling the value of error the corresponding class should be active on my first element.



    Even though the toggling of error works as expected, when inspecting the first element, it doesn't appear that the btn-success class was added.



    Is there something here I'm missing, or can you not add classes to elements like this?



    Also, here is the code I'm using to test this:






    var app = new Vue({
    el: '#app',
    data: {
    error: false,
    classArray: {
    btn: true,
    'btn-success': this.error
    }
    },
    methods: {
    toggle: function() {
    this.error = !this.error;
    console.log(document.getElementById('input1'));
    }
    }
    });

    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    <div id="app">
    <input type='button' id='input1' :class='classArray' value='Submit' />
    <input type='button' @click='toggle' value='Change class' />
    </div>












    share|improve this question

























      0












      0








      0







      I have a Vue instance which has two data properties: error which is initially set to false, and classArray which is an object that contains two classes: btn and btn-success.





      btn is set to true and
      btn-success is set to error, which initially is false.



      I have two input elements, both of which are buttons, where the first one's class is set to classArray.



      The other button, upon clicking, invokes a method attached to my Vue instance that is supposed to toggle error (so if error is true, then it becomes false, and vice versa).



      My expectation is that, because btn-success in classArray is set to the value of error, that upon toggling the value of error the corresponding class should be active on my first element.



      Even though the toggling of error works as expected, when inspecting the first element, it doesn't appear that the btn-success class was added.



      Is there something here I'm missing, or can you not add classes to elements like this?



      Also, here is the code I'm using to test this:






      var app = new Vue({
      el: '#app',
      data: {
      error: false,
      classArray: {
      btn: true,
      'btn-success': this.error
      }
      },
      methods: {
      toggle: function() {
      this.error = !this.error;
      console.log(document.getElementById('input1'));
      }
      }
      });

      <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
      <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
      <div id="app">
      <input type='button' id='input1' :class='classArray' value='Submit' />
      <input type='button' @click='toggle' value='Change class' />
      </div>












      share|improve this question













      I have a Vue instance which has two data properties: error which is initially set to false, and classArray which is an object that contains two classes: btn and btn-success.





      btn is set to true and
      btn-success is set to error, which initially is false.



      I have two input elements, both of which are buttons, where the first one's class is set to classArray.



      The other button, upon clicking, invokes a method attached to my Vue instance that is supposed to toggle error (so if error is true, then it becomes false, and vice versa).



      My expectation is that, because btn-success in classArray is set to the value of error, that upon toggling the value of error the corresponding class should be active on my first element.



      Even though the toggling of error works as expected, when inspecting the first element, it doesn't appear that the btn-success class was added.



      Is there something here I'm missing, or can you not add classes to elements like this?



      Also, here is the code I'm using to test this:






      var app = new Vue({
      el: '#app',
      data: {
      error: false,
      classArray: {
      btn: true,
      'btn-success': this.error
      }
      },
      methods: {
      toggle: function() {
      this.error = !this.error;
      console.log(document.getElementById('input1'));
      }
      }
      });

      <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
      <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
      <div id="app">
      <input type='button' id='input1' :class='classArray' value='Submit' />
      <input type='button' @click='toggle' value='Change class' />
      </div>








      var app = new Vue({
      el: '#app',
      data: {
      error: false,
      classArray: {
      btn: true,
      'btn-success': this.error
      }
      },
      methods: {
      toggle: function() {
      this.error = !this.error;
      console.log(document.getElementById('input1'));
      }
      }
      });

      <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
      <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
      <div id="app">
      <input type='button' id='input1' :class='classArray' value='Submit' />
      <input type='button' @click='toggle' value='Change class' />
      </div>





      var app = new Vue({
      el: '#app',
      data: {
      error: false,
      classArray: {
      btn: true,
      'btn-success': this.error
      }
      },
      methods: {
      toggle: function() {
      this.error = !this.error;
      console.log(document.getElementById('input1'));
      }
      }
      });

      <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
      <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
      <div id="app">
      <input type='button' id='input1' :class='classArray' value='Submit' />
      <input type='button' @click='toggle' value='Change class' />
      </div>






      javascript vue.js






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 '18 at 16:27









      Delfino

      4191623




      4191623
























          1 Answer
          1






          active

          oldest

          votes


















          2














          The problem is that the value of btn-success is set to true only once when the data object is first created and doesn't change after that so changing this.error won't have any effect on classArray. Instead you could set classArray as a computed property and it will update itself whenever this.error is updated.






          var app = new Vue({
          el: '#app',
          computed : {
          classArray(){
          return {
          btn : true,
          'btn-succes' : this.error
          }
          }
          },
          data: {
          error: false,
          },
          methods: {
          toggle: function() {
          this.error = !this.error;
          console.log(document.getElementById('input1'));
          }
          }
          });

          <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
          <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
          <div id="app">
          <input type='button' id='input1' :class='classArray' value='Submit' />
          <input type='button' @click='toggle' value='Change class' />
          </div>





          This is just personal preference, but I personally like to use inline classes in this style (spacing for emphasis).



          <input 
          type='button'
          id='input1'
          :class='["btn", error && "btn-success" ]'
          value='Submit'/>


          Doing it this way means you can avoid adding tons of computed properties when you have a lot more elements that need variable classes.






          share|improve this answer























          • So classArray is re-evaluated every time error changes, then?
            – Delfino
            Nov 21 '18 at 16:37






          • 1




            Yep. With a compouted property Vue is aware that classArray depends on the value of error and will update it whenever error changes. See Here
            – Khauri McClain
            Nov 21 '18 at 16:42










          • Thank you for providing the reference; it's extremely helpful! Also, clever way of handling the class :)
            – Delfino
            Nov 21 '18 at 20:09











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53416485%2fvue-js-change-elements-class-based-on-change-to-data-property%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          The problem is that the value of btn-success is set to true only once when the data object is first created and doesn't change after that so changing this.error won't have any effect on classArray. Instead you could set classArray as a computed property and it will update itself whenever this.error is updated.






          var app = new Vue({
          el: '#app',
          computed : {
          classArray(){
          return {
          btn : true,
          'btn-succes' : this.error
          }
          }
          },
          data: {
          error: false,
          },
          methods: {
          toggle: function() {
          this.error = !this.error;
          console.log(document.getElementById('input1'));
          }
          }
          });

          <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
          <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
          <div id="app">
          <input type='button' id='input1' :class='classArray' value='Submit' />
          <input type='button' @click='toggle' value='Change class' />
          </div>





          This is just personal preference, but I personally like to use inline classes in this style (spacing for emphasis).



          <input 
          type='button'
          id='input1'
          :class='["btn", error && "btn-success" ]'
          value='Submit'/>


          Doing it this way means you can avoid adding tons of computed properties when you have a lot more elements that need variable classes.






          share|improve this answer























          • So classArray is re-evaluated every time error changes, then?
            – Delfino
            Nov 21 '18 at 16:37






          • 1




            Yep. With a compouted property Vue is aware that classArray depends on the value of error and will update it whenever error changes. See Here
            – Khauri McClain
            Nov 21 '18 at 16:42










          • Thank you for providing the reference; it's extremely helpful! Also, clever way of handling the class :)
            – Delfino
            Nov 21 '18 at 20:09
















          2














          The problem is that the value of btn-success is set to true only once when the data object is first created and doesn't change after that so changing this.error won't have any effect on classArray. Instead you could set classArray as a computed property and it will update itself whenever this.error is updated.






          var app = new Vue({
          el: '#app',
          computed : {
          classArray(){
          return {
          btn : true,
          'btn-succes' : this.error
          }
          }
          },
          data: {
          error: false,
          },
          methods: {
          toggle: function() {
          this.error = !this.error;
          console.log(document.getElementById('input1'));
          }
          }
          });

          <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
          <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
          <div id="app">
          <input type='button' id='input1' :class='classArray' value='Submit' />
          <input type='button' @click='toggle' value='Change class' />
          </div>





          This is just personal preference, but I personally like to use inline classes in this style (spacing for emphasis).



          <input 
          type='button'
          id='input1'
          :class='["btn", error && "btn-success" ]'
          value='Submit'/>


          Doing it this way means you can avoid adding tons of computed properties when you have a lot more elements that need variable classes.






          share|improve this answer























          • So classArray is re-evaluated every time error changes, then?
            – Delfino
            Nov 21 '18 at 16:37






          • 1




            Yep. With a compouted property Vue is aware that classArray depends on the value of error and will update it whenever error changes. See Here
            – Khauri McClain
            Nov 21 '18 at 16:42










          • Thank you for providing the reference; it's extremely helpful! Also, clever way of handling the class :)
            – Delfino
            Nov 21 '18 at 20:09














          2












          2








          2






          The problem is that the value of btn-success is set to true only once when the data object is first created and doesn't change after that so changing this.error won't have any effect on classArray. Instead you could set classArray as a computed property and it will update itself whenever this.error is updated.






          var app = new Vue({
          el: '#app',
          computed : {
          classArray(){
          return {
          btn : true,
          'btn-succes' : this.error
          }
          }
          },
          data: {
          error: false,
          },
          methods: {
          toggle: function() {
          this.error = !this.error;
          console.log(document.getElementById('input1'));
          }
          }
          });

          <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
          <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
          <div id="app">
          <input type='button' id='input1' :class='classArray' value='Submit' />
          <input type='button' @click='toggle' value='Change class' />
          </div>





          This is just personal preference, but I personally like to use inline classes in this style (spacing for emphasis).



          <input 
          type='button'
          id='input1'
          :class='["btn", error && "btn-success" ]'
          value='Submit'/>


          Doing it this way means you can avoid adding tons of computed properties when you have a lot more elements that need variable classes.






          share|improve this answer














          The problem is that the value of btn-success is set to true only once when the data object is first created and doesn't change after that so changing this.error won't have any effect on classArray. Instead you could set classArray as a computed property and it will update itself whenever this.error is updated.






          var app = new Vue({
          el: '#app',
          computed : {
          classArray(){
          return {
          btn : true,
          'btn-succes' : this.error
          }
          }
          },
          data: {
          error: false,
          },
          methods: {
          toggle: function() {
          this.error = !this.error;
          console.log(document.getElementById('input1'));
          }
          }
          });

          <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
          <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
          <div id="app">
          <input type='button' id='input1' :class='classArray' value='Submit' />
          <input type='button' @click='toggle' value='Change class' />
          </div>





          This is just personal preference, but I personally like to use inline classes in this style (spacing for emphasis).



          <input 
          type='button'
          id='input1'
          :class='["btn", error && "btn-success" ]'
          value='Submit'/>


          Doing it this way means you can avoid adding tons of computed properties when you have a lot more elements that need variable classes.






          var app = new Vue({
          el: '#app',
          computed : {
          classArray(){
          return {
          btn : true,
          'btn-succes' : this.error
          }
          }
          },
          data: {
          error: false,
          },
          methods: {
          toggle: function() {
          this.error = !this.error;
          console.log(document.getElementById('input1'));
          }
          }
          });

          <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
          <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
          <div id="app">
          <input type='button' id='input1' :class='classArray' value='Submit' />
          <input type='button' @click='toggle' value='Change class' />
          </div>





          var app = new Vue({
          el: '#app',
          computed : {
          classArray(){
          return {
          btn : true,
          'btn-succes' : this.error
          }
          }
          },
          data: {
          error: false,
          },
          methods: {
          toggle: function() {
          this.error = !this.error;
          console.log(document.getElementById('input1'));
          }
          }
          });

          <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
          <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
          <div id="app">
          <input type='button' id='input1' :class='classArray' value='Submit' />
          <input type='button' @click='toggle' value='Change class' />
          </div>






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 '18 at 16:40

























          answered Nov 21 '18 at 16:35









          Khauri McClain

          2,0961414




          2,0961414












          • So classArray is re-evaluated every time error changes, then?
            – Delfino
            Nov 21 '18 at 16:37






          • 1




            Yep. With a compouted property Vue is aware that classArray depends on the value of error and will update it whenever error changes. See Here
            – Khauri McClain
            Nov 21 '18 at 16:42










          • Thank you for providing the reference; it's extremely helpful! Also, clever way of handling the class :)
            – Delfino
            Nov 21 '18 at 20:09


















          • So classArray is re-evaluated every time error changes, then?
            – Delfino
            Nov 21 '18 at 16:37






          • 1




            Yep. With a compouted property Vue is aware that classArray depends on the value of error and will update it whenever error changes. See Here
            – Khauri McClain
            Nov 21 '18 at 16:42










          • Thank you for providing the reference; it's extremely helpful! Also, clever way of handling the class :)
            – Delfino
            Nov 21 '18 at 20:09
















          So classArray is re-evaluated every time error changes, then?
          – Delfino
          Nov 21 '18 at 16:37




          So classArray is re-evaluated every time error changes, then?
          – Delfino
          Nov 21 '18 at 16:37




          1




          1




          Yep. With a compouted property Vue is aware that classArray depends on the value of error and will update it whenever error changes. See Here
          – Khauri McClain
          Nov 21 '18 at 16:42




          Yep. With a compouted property Vue is aware that classArray depends on the value of error and will update it whenever error changes. See Here
          – Khauri McClain
          Nov 21 '18 at 16:42












          Thank you for providing the reference; it's extremely helpful! Also, clever way of handling the class :)
          – Delfino
          Nov 21 '18 at 20:09




          Thank you for providing the reference; it's extremely helpful! Also, clever way of handling the class :)
          – Delfino
          Nov 21 '18 at 20:09


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53416485%2fvue-js-change-elements-class-based-on-change-to-data-property%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          Refactoring coordinates for Minecraft Pi buildings written in Python