Home > other >  Vuejs passing props to from parents component to child component not working
Vuejs passing props to from parents component to child component not working

Time:11-17

I am newbie and in charge a project using Vuejs.

Here is a page that use a component called DashboardCard and each DardboardCard is passed 2 props is val and icon from the page a.k.a the parent component

dashboard

I declared props in DashboardCard component a.k.a child component but the value of all props can not be passed and assigned

DashboardCard

I now I got this error

error

UPDATE Here is the Vuejs devtool log, you can see that props was passed enter image description here

CodePudding user response:

The reason, is that before even the props hold the value, you are trying to access it. So there are two ways I would suggest

From parent component (Dashboard.vue):

Try passing it like :icon="'@/assets/sale.png'" and :val="'$700'"

and in child Component (DashboardCard.vue)

Method-1:

Declare two data variables and set them with the prop values using watch handler

export default {
 components: {DatePicker},
 props: {
   icon: {
     type: String,
     default: ''
   },
   val: {
     type: String,
     default: ''
   }
 },
 data() {
  return {
    iconPath: '',
    amtVal: ''
  };
 },
 watch: {
  icon(newVal, oldVal) {
    this.iconPath = newVal;
  },
  val(newVal, oldVal) {
    this.amtVal = newVal;
  }
 }

and in template use your local data variables like

<span>{{amtVal}}</span>

and

<img :src="require(iconPath)" alt="icon" />

Method-2:

Using a computed property

export default {
 components: {DatePicker},
 props: {
   icon: {
     type: String,
     default: ''
   },
   val: {
     type: String,
     default: ''
   }
 },
 computed: {
   getIcon() {
     return this.icon;
   },
   getVal() {
    return this.val;
   }
 }

and in template

<span>{{getVal}}</span>

and

<img :src="require(getIcon)" alt="icon" />

CodePudding user response:

You are missing the script ending tag </script> in the DashboardCard component so Vue can't spot out the component properties. At first, I thought there was more code down there until I try the sandbox.

Please note that in the Vue devtools extension, a prop is supposed to sit under the props tab, which is not your case.

I suggest you using some kind of snippets to avoid this annoying typos. For me I use Vetur. It also helps with syntax highlighting, pretty handy extension.

https://marketplace.visualstudio.com/items?itemName=octref.vetur

  • Related