Home > other >  Receive passed data in vue component
Receive passed data in vue component

Time:06-23

I'm trying, with no luck to use some data that get passed into a vue component. I have no problem receiving it, but i don't get how i can manipulate it the way i want.

In the component i want to se its "title" variable to the value passed, if any. But if no value is passed i want to set it to a default value, which in this case is "lorem". I cant use the props default value attribute for a reason that does not matter here.

How would i do this?

Code:

<Meta title="test" />

Component:

<template>
  <div></div>
</template>
<script>
export default {
  name: "Meta",
  data() {
    return {
      title: ""
    };
  },
  computed: {
    thetitle() {
      return this.title ? "" : "lorem ipsum";
    }
  },
  mounted() {
    document
      .querySelector('meta[name="description"]')
      .setAttribute("content", this.title);
  }
};

CodePudding user response:

title should be defined inside the props option since it's received from the parent component :


export default {
  name: "Meta",
  props:['title'];
  computed: {
    thetitle() {
      return this.title ? "" : "lorem ipsum";
    }
  },
  mounted() {
    document
      .querySelector('meta[name="description"]')
      .setAttribute("content", this.title);
  }
};

CodePudding user response:

let's take some scenario to understand this.

export default {
  name: "Meta",
  props:{
    title: {
       type: [String,null,undefined],
       defualt: 'lorem'
    }
  };
  computed: {
    modifiedTitle() {
      return this.title || "lorem ipsum";
    }
  },
  mounted() {
    document
      .querySelector('meta[name="description"]')
      .setAttribute("content", this.modifiedTitle);
  }
};

1. test="randon truethy string"

<Meta title="test" />

here we are passing a string in title. so the default function of title props will not call. and in modified title props this.title get truthy value .so return value of modifiedTitle is 'randon truthy string'

2.test ="" or null

<Meta title="test" />

here we are passing a string as an empty string or null. even in this case also default function will not call. and modifiedTitle props this.title is falsy value so these will return "lorem ipsum".

3.pass test = undefined

   <Meta title="test" />

here we are passing undefined. so in this case default function of props is called as a set default value to the title which is "lorem". in modifiedTitle props this.title has truthy value (which is set by default function -> 'lorem'). so modified computedProps return 'lorem'

4. Don't pass the test as props

<Meta />

in this, we are not passing props. so it will call the default function and further value set according to point 3. it also returns 'lorem' in modifiedTitle props.

  • Related