1

I need to pass down a variable to a component. My setup is like this:

Main: Meet.vue

<html>
 <div class="carousel-cell">
    <Category :searchTerm="woman"></Category>
    </div>
 <div class="carousel-cell">
    <Category :searchTerm="men"></Category>
    </div>
[..]
<script>
import Category from './Category'
export default {
  components: {
    Category
  },

Sub: Category.vue:

export default {
  data () {
    return {
      search: [how to access the **searchTerm** here?]

How to access the searchTerm <Category :searchTerm="woman"></Category> from Meet.vue in Category.vue?

Tom
  • 5,588
  • 20
  • 77
  • 129

3 Answers3

4

You'll have to introduce this searchTerm property in your Category component as described in the VueJS Documentation

In Category.vue

export default {
  props: ['searchTerm'],

  // Your component code (computed, methods, watch, ...)
}

If you want to apply some validation on your prop

export default {
  props: {
    searchTerm: {
      type: String,
      required: false,
      // If not required, it's possible to give a default value
      default: "woman"
    },
  }

  // Your component code (computed, methods, watch, ...)
}

You can then read your prop with this.searchTerm. You can also directly read it inside <template></template> with {{ searchTerm }} for example.


If at some point you'll need to write on one of your prop, it is best to copy it's value on a local variable and work with it

props: ['searchTerm'],
data: function () {
  return {
    // Write on search variable if needed
    search: this.searchTerm
  }
}
Cédric M.
  • 1,142
  • 3
  • 12
  • 23
  • Thank you for this example. Is there a way to pass the **searchTerm** after it changed in the **meet.vue**? I tried __v-bind__ without success: `` – Tom Apr 28 '19 at 11:25
  • 1
    @Tom I suggest you to watch your prop in your Category component. You can have an example here https://stackoverflow.com/questions/44584292/vuejs-2-0-how-to-listen-for-props-changes - and you can check the documentation to understand how it works : https://vuejs.org/v2/guide/computed.html#Computed-vs-Watched-Property – Cédric M. Apr 29 '19 at 08:11
1

You are using props, so the answer is:

export default{
    props: ['searchTerm'],

it can then be used directly.

tony19
  • 125,647
  • 18
  • 229
  • 307
Ketzu
  • 660
  • 1
  • 7
  • 12
1

Do as below while calling the Category component.

<Category :search="woman"></Category>

Here :search:"woman" means pass woman as value to the property of Category component.

Then in Category component:

export default {
  props: {
    search: {type: string, required: true}
    //Here it will give error if the search is passed anything but string
    //And if search is not passed it will give error. 
  }
  //Everything else

or

export default {
  props: [search], //No checking of data type and it's not requried
  //Everything else
Imran
  • 4,582
  • 2
  • 18
  • 37