首页 > 解决方案 > Vue 在创建新组件时丢失原型和导入的文件

问题描述

将 Vue 组件扩展为 modal 时,会生成一个新的 Vue 实例。这会导致丢失所有预先导入的助手/Vuex-stores 等。

有没有办法将所有数据复制到新的扩展 Vue 组件?

为了清楚起见,看看这个jsfiddle

它会向您发出警报。当您单击按钮时,将打开模式。但是,如果您查看我的代码,应该会触发另一个警报。但是 $hi() 在其他 Vue 实例中不可用。

我创建了一个这样的组件:

const createComponent = (props) => {
    const wrapper = document.createElement('div');

    const Component = Vue.extend(MyComponent);

    return new Component({
        propsData: {
            props,
        },
    }).$mount(wrapper);
};

我使用SweetAlert作为模式。

所以我像这样添加:

swal({
    content: createComponent(props).$el,
})

标签: vue.js

解决方案


如果你移动这条线

Vue.prototype.$hi = () => alert('hi');

以上

let component = new TestComponent().$mount(wrapper)

它会起作用的。您的第一个组件$hi()在定义之前引用。


推荐阅读