ramazan793
ramazan793

Reputation: 689

Use a Vue JS component method in another vue comonent

I have a two different vue component files, what should i do in order to use a changeCollection() method from Check-list.vue in another Component.vue file?

Check-lust.vue:

<template lang="html" ref="">
  <div class="check-list-view">
    <collections :current_collection="this.current_collection" ></collections>
  </div>
</template>

<script>
export default {
  data () {
    return {
      current_collection: 'All'
    }
  },
  methods: {
    changeCollection (collname) {
      this.current_collection = collname
    }
  }
}
</script>

And Component.vue:

<template lang="html">
  <div class="container " style="margin-bottom:32px">
    <!-- NOT WORKS: -->
    <button type="button" name="button" class="btn my-btn-orange" @click="changeCollection('All')">All</button>
  </div>
</template>

<script>

export default {
  props: ['current_collection']
}
</script>

Upvotes: 1

Views: 124

Answers (1)

LiranC
LiranC

Reputation: 2480

Define a mixin.

mixin.js

export default {
  methods: {
    changeCollection(collname) {
      this.current_collection = collname
    }
  }
}

Check-lust.vue:

<template lang="html" ref="">
  <div class="check-list-view">
    <!-- changeCollection should be available here now -->
    <collections @click="changeCollection">hello world</collections>
  </div>
</template>
<script>
import mixin from './mixin.js' //import the mixin
export default {
  data () {
    return {
      current_collection: 'All'
    }
  },
  mixins:[mixin], // include the mixin in your component
  methods: {
    changeCollection (collname) {
      this.current_collection = collname
    }
  }
}
</script>

repeat the import of mixin.js on the rest of your components, and define mixins property on those as well.

ChangeCollection will be available on each component.

Upvotes: 5

Related Questions