Home > Back-end >  v-if --> props as object property
v-if --> props as object property

Time:05-31

From my parent component I do something like this:

<example myID="abcd1234" label="Something important" />
<example myID="87poi" label="Just a label" />
<example myID="zxcvb" label="Extremely important" />
<example myID="bcd" label="No importance at all" />

And following is my child component:

<template>
  <div>
    <label :id="[myID]">{{ label }}</label>
    <input :id="[myID]" type="text" v-on:focusout="handleFocusOut"/>
    <div v-if="errors.myID">{{errors.myID}}</div> //this line does not work.
    // <div v-if="errors[myID]">{{errors.myID}}</div> //neither does this

  </div>
</template>

<script>
export default {
  name: 'example',
  data() { return { errors: {} } },
  props: { myID: String, label: String },
  methods: {
    handleFocusOut(e) {
      console.log('I am in onFocusOut')
      let myCurrentID = e.target.id
      this.errors[myCurrentID] = 'This is some text'
    }
  }
}
</script>

This line <div v-if="errors.myID"> does not work. How do I pass a prop value to the errors object? Like the way I have written.

Please excuse for the poor code as I am just 2 weeks days old to vue.

CodePudding user response:

Please take a look at following snippet:

Vue.component('example', {
  template: `
    <div>
      <label :for="myID">{{ label }}</label>
      <input :id="myID" type="text" @focusout="handleFocusOut"/>
      <div v-if="errors[myID]">{{ errors[myID] }}</div>
    </div>
  `,
  data() { return { errors: {} } },
  props: { myID: String, label: String },
  methods: {
    handleFocusOut() {
      console.log('I am in onFocusOut')
      this.errors = {[this.myID]: 'This is some text'}
    }
  }
})
new Vue({
  el: "#demo"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <example my-i-d="abcd1234" label="Something important"></example>
  <example my-i-d="87poi" label="Just a label"></example>
  <example my-i-d="zxcvb" label="Extremely important"></example>
  <example my-i-d="bcd" label="No importance at all"></example>
</div>

  • Related