Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue动态(new)创建组件实例 #13

Open
masterkong opened this issue Jul 8, 2019 · 0 comments
Open

Vue动态(new)创建组件实例 #13

masterkong opened this issue Jul 8, 2019 · 0 comments
Labels

Comments

@masterkong
Copy link
Owner

Vue动态(new)创建组件实例

前言

Vue组件的按需加载除了通过Webpack的异步组件,还可以有下面这种更原始的new方法。
文档在介绍 propsData 创建实例时也有提及。

实现

import originComp from './originComp'

let Comp = Vue.extend(originComp);

let instance = new Comp({
  el: document.createElement('div'), 
  propsData: { //注意这里一定要用propsData
    msg: 'hello'
  },
  data: {
     hidden: true
  },
  // store: store //设置Vuex
})

/*  1、$on监听内部事件
 *  2、close事件演示了如何销毁组件
 */
instance.$on('close', () => {
    instance.$el.parentNode.removeChild(instance.$el);
    instance.$destroy();
    instance = null;
 })

//也可以挂载在已有的dom节点
//document.getElementById('app').appendChild(instance.$el)
document.body.appendChild(instance.$el)
@masterkong masterkong added the Vue label Jul 8, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant