VueJS:注册组件并从插件访问它

时间:2018-04-03 18:20:21

标签: javascript vue.js vue-component

我正在编写一个允许用户选择数字签名证书的插件。证书来自另一个插件。 我得到了CertificateDialogComponent,代码如下:

<template>
    <el-dialog
            ref="dialog"
            title="Choose Certificate"
            :visible.sync="show"
            append-to-body
            :before-close="hideDialog"
            width="40%">
        <el-table
                ref="table"
                :data="certificates"
                stripe
                style="width: 100%">
            <el-table-column
                    prop="subject"
                    label="Subject">
            </el-table-column>
            <el-table-column
                    prop="thumb"
                    label="Thumb">
            </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
            <el-button @click="hideDialog">Cancel</el-button>
        </span>
    </el-dialog>
</template>
<script>
  import {Dialog, Table, TableColumn, Button} from 'element-ui'
  export default {
    name: 'certificate-dialog',
    components: {
      [Dialog.name]: Dialog,
      [Table.name]: Table,
      [TableColumn.name]: TableColumn,
      [Button.name]: Button
    },
    data () {
      return {
        show: false,
        certificates: []
      }
    },
    methods: {
      selectCertificate (certs) {
        return new Promise((resolve, reject) => {
          this.certificates = certs
          this.show = true
          this.$refs.table.$on('row-click', (row) => {
            this.show = false
            resolve(row)
          })
          this.$refs.dialog.$on('close', () => {
            reject(new Error('Closed By User'))
          })
          this.$on('close', () => {
            reject(new Error('Closed By User'))
          })
        })
      },
      hideDialog () {
        this.show = false
        this.$emit('close')
      }
    }
  }
</script>

当用户点击行时,此组件会发出“已选择”的事件。选择证书。 在我需要的每个其他组件中导入此组件很容易,但我经常需要它。我想创建全局方法getCertificate,它可以打开这个对话框,而不必每次都注册它,并且可以访问这个组件的内部方法selectCertificate。

很抱歉,如果我没有解释清楚,英语不是我的母语,请随时提出任何问题。

1 个答案:

答案 0 :(得分:0)

所以,我设法做到了,但不是按照我想要的方式。 我在CertificateDialog组件中创建了我需要的方法,将此组件添加到App组件,创建了对该方法的引用并使用了提供选项:

<template>
  <certificate-dialog ref="certificateDialog"/>
</template>
<script>
  methods: {
    getCertificate () {
      return this.$refs.certificateDialog.getCertificate()
    },
    signData () {
      return this.$refs.certificateDialog.signData()
    }
  }
  provide () {
    getCertificate: this.getCertificate,
    signData: this.signData
  }
</script>

现在我可以在我想要的每个组件中使用这些方法。它很简单,使用Vue功能,但不是&#34; mobile&#34;和redistributable作为插件可以。但这很有效,所以