记录工作实践
最近在学Vue项目, 对于根组件App.vue通过render函数渲染最终挂载到id为app的dom节点上感觉比较陌生, 那它能挂载其他普通组件吗? 试试看.
简单Vue项目Vue_proj_01
项目结构
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<link rel="icon" href="<%= BASE_URL %>favicon.ico" />
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong
>We're sorry but vue_proj_01 doesn't work properly without JavaScript
enabled. Please enable it to continue.</strong
>
</noscript>
<div id="app">123</div>
<!-- built files will be auto injected -->
</body>
</html>
html-webpack-plugin指定pubic/index.html作为模板生成一个新的index.html文件打包到dist目录, 插件默认title为Webpack App, 修改它要配置vue.config.js
vue.config.js
通过配置html插件的属性名title, 将它的属性值改为项目名即可
新打包生成的index.html中保留了id为app的div元素, 其中的内容为123
项目入口文件main.js
import Vue from 'vue'
import App from './App.vue'
import MessageBox from './components/MessageBox.vue'
Vue.config.productionTip = false
new Vue({
render: (h) => h(App),
}).$mount('#app0')
MessageBox是一个普通组件
我故意将挂载根组件的节点id写错, 说明挂载不上, 看看什么效果
title已经变成了配置文件中修改的vue_proj_01
因为挂载根组件失败, 目前显示的还是index.html中原始内容
new Vue({
render: (h) => h(App),
}).$mount('#app')
修改将要挂载的正确节点id
根组件App.vue
<template>
<div id="app1">App根组件</div>
</template>
<style></style>
检查-->元素
render函数用根组件在id为app的节点上重新渲染, 替换掉了原来的节点
普通组件 MessageBox.vue
<template>
<div>信息窗口</div>
</template>
<script>
export default {
data() {
return {}
},
}
</script>
<style></style>
main.js中引入MessageBox组件, 并将它挂载到一个div元素上
import Vue from 'vue'
import App from './App.vue'
import MessageBox from './components/MessageBox.vue'
Vue.config.productionTip = false
new Vue({
render: (h) => h(App),
}).$mount('#app')
// 创建div元素节点
const div = document.createElement('div')
// 将创建的div节点追加到id为app1的父节点下的所有子节点后面
document.getElementById('app1').appendChild(div)
new Vue({
// 渲染MessageBox组件
render: (h) => h(MessageBox),
// 在div节点处渲染
}).$mount(div)
总结: 普通组件也能像根组件一样通过render函数进行渲染, 挂载到某个节点上.