How to access individual elements from a prop object in Vue

我们两清 提交于 2021-01-29 07:08:23

问题


I am new to Vue and studied the other questions here and can not seem to work out how to pass an object to a child component and reference individual elements of that object. I want all elements of the object to be able to be individually accessed and used in the footer template where appropriate. I am using NPM from node-js and run the dev with npm run dev

In my root component, App.Vue, I have as follows: (unrelated lines omitted)

<template>
<div>
  <router-view></router-view>
  <bbay-footer v-bind:footerData="footerData"></bbay-footer>
</div>
</template>

<script>
import Footer from './Components/SiteWide/Footer.vue'

export default {
  components: {
    'bbay-footer': Footer,
  },
  data() {
    return {
        footerData: [{
                titleFooter: 'My Computer Support',
                mainNumber: '0411111111',
                otherNumber: '0400000000',
                emailUs: 'mailto:info@mycomputersupport.com'
      }]
    }
  }
}
</script>

Now in Footer.vue I have:

<template>
  <footer>
   <p>{{startCR}} - {{copyright}} </p>
  </footer>
</template>

<script>
export default {
  props: {
    titleFooter: String,
    mainNumber: Number,
    otherNumber: Number,
    emailUs: String
  },

  data () {
    return {
      copyright: "Copyright 2020: ",
      startCR: this.footerData.titleFooter,
      mNum: footerData.mainNumber,
      oNum: footerData.otherNumber,
      emailUs: footerData.emailUs
    }
  },
}
</script>

回答1:


You are passing just 1 prop footerData but you have defined 4 in Footer.vue. Just define 1 prop in Footer.vue, and access as this.footerData[0].titleFooter, ...

export default {
 props: {
   footerData: Array,
 },

 data () {
   return {
     copyright: "Copyright 2020: ",
     startCR: this.footerData[0].titleFooter,
     mNum: this.footerData[0].mainNumber,
     oNum: this.footerData[0].otherNumber,
     emailUs: this.footerData[0].emailUs
   }
 },
}

You can handle the array in Footer.vue. You should define as many props as v-bind you are sending. https://vuejs.org/v2/guide/components.html#Passing-Data-to-Child-Components-with-Props



来源:https://stackoverflow.com/questions/63917451/how-to-access-individual-elements-from-a-prop-object-in-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!