[Vuejs]-How to point out this to a certain element in VueJS?

2👍

I have a simpler alternative that gives more flexibility

new Vue({
  el: '#app',
  props: ['styles'],
  methods: {
    changeStyles() {
      this.styles = {
        color: 'blue'    // Add more CSS rules if you want
      }
    },
    restoreStyles() {
      this.styles = {
        color: 'black'
      }
    }
  }
})
<div id="app">
  <label :style="styles">Input</label>
  <input type="text" @focus="changeStyles" @focusout="restoreStyles">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>

Hope it helps. And the for attribute in label tag only works with id of the bound input field.

0👍

Check the console output of this snippet:

new Vue({
  el: '#app',
  data: {
    inputs: document.querySelector('.input')
  },
  methods: {
    changeColor(){
      console.log('Are the similar? answer: ', 
             this.inputs == document.querySelector('.input')); 
      this.inputs.previousElementSibling.style.color = "blue";
    }
  }
});
<div id="app">
    <label for="input">Input</label>
    <input type="text" class = "input" v-on:focus = "changeColor"><br /><br />
</div>
<script type = "text/javascript" src = "https://vuejs.org/js/vue.js"></script>

After Vue instance is created it replaces all elements inside the #app in its own flavor. Your inputs field is set at the moment of creating Vue instance and before mounting the #app component. So the thing that you store in the this.inputs is long dead!

You should probably read through the Reactivity in Depth very carefully. And as suggested by the @Shreevardhan’s answer, you should always use Vue’s way to manipulate Vue’s stuffs.

👤Dipu

Leave a comment