简体   繁体   English

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

[英]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?我有两个不同的 vue 组件文件,我应该怎么做才能在另一个Component.vue文件中使用Check-list.vue中的 changeCollection changeCollection()方法?

Check-lust.vue :检查 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 :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>

Define a mixin.定义一个mixin。

mixin.js mixin.js

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

Check-lust.vue:检查 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.在其余组件上重复mixin.js的导入,并在这些组件上定义mixins属性。

ChangeCollection will be available on each component. ChangeCollection将在每个组件上可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM