Vue组件通过Vue.component注册后在.cshtml页面标签无法渲染的问题排查与解决
Hey everyone, I wanted to share a problem I faced using a Vue component in a .cshtml page, plus the solutions I found along the way.
First, some context: I have a component MyOwnComponent.vue that works great inside other Vue files. Inside it, I register a file upload component like this, and it renders perfectly:
import fileUploader from '../common/FileUploader.vue'; Vue.component('file-uploader', fileUploader);
When I needed to use MyOwnComponent.vue directly in a .cshtml page, this approach worked flawlessly:
import cmpMyOwnComponent from '../vue/cmpMyOwnComponent.vue'; window.MyOwnComponent = (function(){ let vueApp = Vue.extend(cmpMyOwnComponent); return new vueApp().$mount('#my-own-component'); })();
But I tried to simplify things by registering the component globally instead:
Vue.component('my-own-component', myOwnComponent);
I set the component's name property to 'my-own-component' and used <my-own-component></my-own-component> in the .cshtml— but the component didn’t render at all. No console errors, no feedback, just nothing.
How I Fixed It
Update 1: Quick Fix (But Extra DOM Element)
First, I got it working by wrapping the component tag in a div container:
<div id="div-my-own-component"> <my-own-component></my-own-component> </div>
Then initializing a Vue instance that targets that div:
new Vue({ el: '#div-my-own-component' });
The root issue? I’d registered the component, but never created a Vue instance to mount the component tree. This fixed it, but I didn’t love adding an extra div just for this— it actually made my code more verbose than the original working method, so I went back to my initial approach for a bit.
Update 2: Cleaner, No Extra DOM Element
Later, I realized I didn’t need the extra div at all! I can mount the Vue instance directly to the component tag itself:
new Vue({ el: 'my-own-component' });
This works perfectly, no extra container required.
内容的提问来源于stack exchange,提问作者Jay

