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

标签 javascript vue.js vuejs2 vue-component

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

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>

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.js

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

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

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

ChangeCollection 将在每个组件上可用。

关于javascript - 在另一个 vue 组件中使用 Vue JS 组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46798062/

相关文章:

vue.js - Vuejs : is it possible to name Vue instances in vue-devtools?

javascript - Vue.js/Nuxt.js - 如何将 props 传递到 slot?

javascript - 将表格 td 乘以输入

javascript - 扩展 Javascript 对象功能集

javascript - Vue for 循环内的绑定(bind)元素无法正常工作

javascript - Vue.js v-for 数组上的循环不起作用(零元素,非零长度)

javascript - Firebase 是否发送给定路径下的所有数据?

javascript - 类型错误 : Cannot read property 'rtl' of undefined

javascript - 模式选项卡在第一次触发时无法正确加载

javascript - Firebase 参数太多。运行 firebase 帮助模拟器 :start for usage instructions