[TOC] >[success] # Vue -- 手动挂载组件位置 [关于挂载的底层原理代码的解析介绍](https://juejin.im/post/59da1c116fb9a00a4a4cf6dd) ~~~ 1.现在要解决的是如何让我们的组件的可以定义其所在的渲染范围,因为平常在我们写单页面的时候,我们经常 在入口文件会写的以下代码: import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' new Vue({ router, store, render: h => h(App) }).$mount('#app') 或者是: new Vue({ el:'#app', router, store, render: h => h(App) }) ~~~ ~~~ 1.可以发现我们的单页面主体一般我们可以通过'el'的形式也好或者是'$mount'的形式也好我们将其限制在一个 范围内,如果我们的另外的组件想脱离这个范围或者是指定渲染范围可以通过'extend' 和'$mount' ~~~ >[danger] ##### Vue.extend 创建一个未挂载的组件 [vue 文档 对extend 详细讲解](https://cn.vuejs.org/v2/api/#ignoredElements) ~~~ 1.在之前的章节里有讲 'Vue.extend' 创建组件的用法https://www.kancloud.cn/cyyspring/vuejs/936914#Vueextend___33 2.要明确一点Vue.extend 可以创建一个未挂载的组件 ~~~ >[danger] ##### 使用 $mount 来挂载未被挂载的组件 [vue 文档的讲解vm-mount](https://cn.vuejs.org/v2/api/#vm-mount) * 将一个未被挂载的组件挂载到body 标签上 ~~~ 1.挂载body 的过程少许有些不同 首先我们调用了 '$mount' 方法对组件进行了手动渲染,但它仅仅是被渲染好了,并没有挂载到节点上, 也就显示不了组件。此时的 component 已经是一个标准的 Vue 组件实例,因此它的 '$el' 属性也可以被访问 我们拿到'$el'后就可以直接将组件组件插入进'document.body' 中 ~~~ ~~~ import Vue from 'vue'; const AlertComponent = Vue.extend({ template: '<div>{{ message }}</div>', data () { return { message: 'Hello, Aresn' }; }, }); const component = new AlertComponent().$mount(); document.body.appendChild(component.$el); ~~~ >[info] ## 简写 ~~~ 1.其实可以参看我们用cli 脚手架的时候明显可以看出来,这里的组件注册明显没有使用'extend' 而是单独使用 一个vue 实例配合render 函数,因此我们也可使用这种方法来简写一个将未注册组件挂载到页面的方法 ~~~ ~~~ import Vue from 'vue'; import Notification from './notification.vue'; const props = {}; // 这里可以传入一些组件的 props 选项 const Instance = new Vue({ render (h) { return h(Notification, { props: props }); } }); const component = Instance.$mount(); document.body.appendChild(component.$el); ~~~ >[danger] ##### 如何使用 ~~~ 1.如果想操作 Render 的 Notification 实例,可以直接从实例利用$children 取出来,当然这是一个数组,可以 对组件增加一些属性标记这样就可以从数组中取出自己准备想要的组件,因为上面的案例只有一个因此直接、 取第一个 const notification = Instance.$children[0]; ~~~ 注: ~~~ 1.需要注意的是,我们是用 $mount 手动渲染的组件,如果要销毁,也要用 $destroy 来手动销毁实例, 必要时,也可以用 removeChild 把节点从 DOM 中移除。 ~~~