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

时间:2017-10-17 19:47:47

标签: javascript vue.js vuejs2 vue-component

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

检查-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>

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>

1 个答案:

答案 0 :(得分:5)

Define a mixin.

<强> mixin.js

coef

检查-lust.vue:

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

在其余组件上重复导入<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> ,并在这些组件上定义mixin.js属性。

mixins将在每个组件上提供。