首页 > 解决方案 > 如何从组件创建 Vue.prototype?

问题描述

请帮助,如何从组件创建 Vue.prototype,

当调用 this.$authen.check() 响应 this.$store ... 未定义。

我如何使用 Vue.extend 附加 vue global

谢谢你。

对话.vue

<template>
</template> 

<script>
export default {
  name: 'AuthenDialog',
  data: () => ({
    state: 0,
  }),

  methods: {
    check() {
      console.log(this.$store) // is undefined
    },
  }

  // when i use this it work!
  /*beforeCreate() {
    Vue.authen = Vue.prototype.$authen = this
  }*/
}
</script>

@/plugins/AuthenDialog.js

import Vue from 'vue' 
import AuthenDialog from './Dialog'
AuthenDialog.install = (Vue, options) => {
    Vue.component(AuthenDialog.name, AuthenDialog)

    Vue.authen = Vue.prototype.$authen = new Vue.extend(AuthenDialog)
}

Vue.use(AuthenDialog)

标签: vue.jsnuxt.js

解决方案


尝试在 created 钩子上定义一个数据属性作为存储:

{
data: () => ({
    store: null,
  }),

methods: {
    check() {
      console.log(store)
    },
  },

created() {
    this.state = this.$store
  }
}

并像这样安装插件

AuthenDialog.install = (Vue, options) => {
   Object.defineProperty(Vue.prototype, '$authen', new Vue.extend(AuthenDialog))
}

推荐阅读