You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC视图中Vue自定义组件无法渲染的问题求助

问题分析

你当前的核心问题是:当使用空的App.vue或{}作为Vue根组件时,根组件模板无内容,Vue只会渲染根组件自身的模板,不会自动编译挂载容器(#app2)内的原始DOM。即便全局注册了ContractorList组件,MVC视图里写的<ContractorList/>属于挂载容器内的外部DOM,无法被Vue识别处理——除非根组件提供渲染这些内容的逻辑,或者启用运行时编译让Vue直接编译容器内的DOM。


解决方案1:通过插槽渲染容器内内容(推荐,无需修改构建配置)

利用Vue的插槽特性,让根组件自动渲染挂载容器内的所有内容,无需额外编译配置:

  1. 修改App.vue,添加默认插槽
<template>
  <!-- 默认插槽会自动渲染挂载容器内的所有内容 -->
  <slot></slot>
</template>

<script setup lang="ts">
// 无需在此导入ContractorList,已在main.ts全局注册
</script>
  1. 保持main.ts的全局组件注册逻辑
import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import PrimeVue from 'primevue/config';
import App from './App.vue'
import ContractorList from './components/lookup-lists/ContractorList.vue'

const app2 = createApp(App)
app2.use(createPinia())
app2.use(PrimeVue)
// 全局注册组件,使其在整个Vue应用中可用
app2.component('ContractorList', ContractorList)
app2.mount('#app2')
  1. 清理MVC视图的脚本引入
    移除多余的vue.global.min.js,避免版本冲突(你的构建产物已包含Vue运行时):
<div class="row mb-2">
    <div class="col-6">
        <div id="app2">
            <ContractorList/>
        </div>
    </div>
</div>

<!-- 仅引入自己构建的Vue产物 -->
<script src="~/VueJs/dist/[app-name].js"></script>

此时Vue挂载到#app2后,根组件的插槽会自动渲染容器内的<ContractorList/>,全局注册的组件会被正确识别并渲染。


解决方案2:启用运行时编译直接编译容器DOM

如果不想修改App.vue,可启用Vue运行时编译功能,让Vue直接处理挂载容器内的原始DOM:

  1. 配置Vue项目支持运行时编译

    • 若使用Vite,修改vite.config.ts:
      import { defineConfig } from 'vite'
      import vue from '@vitejs/plugin-vue'
      
      export default defineConfig({
        plugins: [vue()],
        resolve: {
          alias: {
            'vue': 'vue/dist/vue.esm-bundler.js' // 指向包含编译器的Vue版本
          }
        }
      })
      
    • 若使用Vue CLI,修改vue.config.js:
      module.exports = {
        runtimeCompiler: true
      }
      
  2. 修改main.ts,直接编译容器内DOM

import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import PrimeVue from 'primevue/config';
import ContractorList from './components/lookup-lists/ContractorList.vue'

const appContainer = document.getElementById('app2')
if (appContainer) {
  // 获取容器内的HTML作为根组件模板
  const template = appContainer.innerHTML
  // 清空容器避免重复渲染
  appContainer.innerHTML = ''
  
  const app2 = createApp({ template })
  app2.use(createPinia())
  app2.use(PrimeVue)
  app2.component('ContractorList', ContractorList)
  app2.mount(appContainer)
}
  1. 同样清理MVC视图的多余脚本引入,仅保留自己的构建产物脚本。

内容的提问来源于stack exchange,提问作者user2283208

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 00:57:12