Home > Back-end >  How to conditionally add values to props?
How to conditionally add values to props?

Time:06-20

How can i use a condition to change the value of these props? In the component i want to set the props value to another one if none are passed. For example, if no title are passed i want to set that to some static string instead. How would i do that?

Component:

<template>
  <vue-headful
    :title="this.title"
    :description="this.description"
    :url="this.url"
    :image="this.image"
/>
</template>
<script>
import vueHeadful from "vue-headful";

export default {
  name: "Meta",
  components: { vueHeadful },
  props: {
    title: String,
    description: String,
    url: String,
    image: String
  }
};

Here's how im using it in another file:

<Meta title="test" />

CodePudding user response:

You can set a default value into each prop:

export default {
  name: "Meta",
  components: { vueHeadful },
  props: {
    title: {
      type: String,
      default: ''
    },
    description: {
      type: String,
      default: 'foo'
    },
    url: {
      type: String,
      default: 'www.example.com'
    },
    image: {
      type: String,
      default: '/some/path'
    }
  }
};

You have a lot of interesting settigs for props in the docs: https://vuejs.org/guide/components/props.html#prop-validation

CodePudding user response:

You can use computed properties:

https://vuejs.org/guide/essentials/computed.html

CodePudding user response:

you can set a default value for title like this:

{
  title: {
    type: String,
    default: 'YOUR DEFAULT TITLE GOES HERE'
  }
}
  • Related