[Vuejs]-Changing vue instance variables from within component

2👍

You shouldn’t attempt to modify props from within a component as Vue’s warnings tell you, changes to props do not flow up from the component to the prop so any changes will be overwritten.

For what you’re trying to achieve you should look into Vue’s Custom Events https://v2.vuejs.org/v2/guide/components-custom-events.html

HTML

<div id="app">
   <form>
        <div>
           <label>Username</label>
           <input type="username" v-model="formData.username" />
           <tooltip :show="tooltips.username.vis" 
    :message="tooltips.username.message" @tooltip:hide="tooltips.username.vis = false" />
        </div>

        <div>
           <label>Password</label>
           <input type="text" v-model="formData.password" />
           <tooltip :show="tooltips.password.vis" 
   :message="tooltips.password.message" @tooltip:hide="tooltips.password.vis = false" />
        </div>
   </form>
</div>

JS

Vue.component('tooltip', {
  props: ['show', 'message'],
  template: `<transition name="shrink">
      <div v-show="show" class="tooltip" @click="hide">
        <div class="tooltip-arrow"></div>
        <div class="tooltip-container">{{message}}</div>
      </div>
    </transition>`,
  methods: {
    hide () {
      this.$emit('tooltip:hide');
    },
  }
}); 

new Vue({
    el: "#app",
    data: {
      formData: {
        username: '',
        password: ''
      },
      tooltips: {
        username: {
            message: 'Fix your username',
            vis: true
        },
        password: {
            message: 'Fix your password',
            vis: true
        }
    }
    }
});

https://jsfiddle.net/10fjkoob/12/

Leave a comment