在另一个vue组件中使用Vue JS组件方法

ram*_*793 1 javascript vue.js vue-component vuejs2

我有两个不同的vue组件文件,我应该怎么做才能在另一个Component.vue文件中使用Check-list.vue中的changeCollection()方法?

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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

Lir*_*anC 5

定义一个mixin.

mixin.js

export default {
  methods: {
    changeCollection(collname) {
      this.current_collection = collname
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

入住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>
Run Code Online (Sandbox Code Playgroud)

重复导入mixin.js其余组件,并mixins在这些组件上定义属性.

ChangeCollection 将在每个组件上提供.