Vue3: Is it possible to register single file components using app.component(...)? - vue.js

Diving into vue 3, trying to add Vue to an existing asp.net core project. Since the frontend is mostly razor pages, the app isn't being mounted with a templated component that has a hierarchy of components.
const vueApp = createApp({});
What I'm trying to do:
vueApp.component('MyComponent', require('./components/MyComponent').default);
vueApp.mount('#app');
I've also tried it this way, as described in the docs:
import { createApp } from 'vue/dist/vue.esm-browser'
import MyComponent from './components/MyComponent.vue'
const vueApp = createApp({
components: {
MyComponent
}
});
vueApp.mount('#app');
I've tried every version of this. requiring MyComponent.vue, with and without the default, importing MyComponent and using it that way (instead of require), none of them work. I just continue getting [Vue warn]: Failed to resolve component 'mycomponent' (Yes I did check the html coming back from the server, It's properly capitalized...not sure why the error is lower case).
MyComponent.vue looks like this:
<template>
<lots of vanilla html>
</template>
<script>
export default {
name: 'MyComponent',
data() {
return { some: "data" }
},
methods: { ... },
mounted() { ...}
}
</script>
//no component styling
Am I missing something here? Or is this no longer possible? I'm using the default vue-cli webpack config, if that matters.
Thanks

So, after rereading the docs (for what feels like the 10th time), I think I figured out the problem. It's actually not a Vue issue at all, it's my use of the Vue component.
In my asp.net core cshtml, I was referencing the component in PascalCase, like this:
<MyComponent />
Turns out this is a no no. By convention (enforced by the browser I guess), custom elements can only be referenced in the DOM using kebab-case, like this:
<my-component />
My vue app is still defining the component in PascalCase.
My main.js file is importing MyComponent, then passing it into the createApp options.components object.
const vueApp = createApp({
components: {
MyComponent
}
});
The more you know, I guess.

Related

Create "literal" component in SFC won't work?

I'm trying to create a dead simple "literal" component(MyComponent in this example) inside a SFC(vue 3):
<template>
<MyComponent>aha</MyComponent>
</template>
<script>
import { ref } from "vue";
const MyComponent = {
name: "MyCompoent",
template: "<h1>aha</h1>",
};
export default {
components: {
MyComponent,
},
};
</script>
But this won't work...
However, if I split the MyComponent into another SFC, it will work.
Anyone knows why and how to fix this?
The template option is ignored because the runtime compiler is disabled by default as an optimization. Using that option would cause a console warning like this:
[Vue warn]: Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias "vue" to "vue/dist/vue.esm-bundler.js".
In Vue CLI generated projects, set the runtimeCompiler flag to enable the template option:
// vue.config.js
module.exports = {
runtimeCompiler: true
}

Import npm package into a Vue.js Single File component

I would like to use Jodit in a SFC, but I am not sure how this is supposed to be done. I realized there is a wrapper (jodit-vue), but for educational purposes, I would like to know how it's done without it. I created a Vue CLI project with default presets, and all I changed is the App.vue:
<template>
<div id="app">
<textarea id="editor" name="editor"></textarea>
</div>
</template>
<script>
import "../node_modules/jodit/build/jodit.min.js"
export default {
name: 'App',
created(){
let editor = new Jodit('#editor');
editor.value = '<p>start</p>';
}
}
</script>
<style>
#import "../node_modules/jodit/build/jodit.min.css" ;
</style>
This produces the error: error 'Jodit' is not defined no-undef, and
if I change the import to:
import Jodit from "../node_modules/jodit/build/jodit.min.js"
Then the compilation is fine, but the browser console says:
vue.runtime.esm.js?2b0e:1888 TypeError: _node_modules_jodit_build_jodit_min_js__WEBPACK_IMPORTED_MODULE_0___default.a is not a constructor
Admittedly, I am new to all of this, but pointing me to the right direction is appreciated.
The jodit module exports the Jodit constructor, so your component would import it like this:
import { Jodit } from 'jodit'
You'd also need the Jodit styles, which could be imported like this:
import 'jodit/build/jodit.min.css'
To create a Jodit instance, we need to provide an element or selector to an existing <textarea>. The Vue component's elements are available in the mounted() lifecycle hook (not in the created() hook), so that's where we would initialize:
export default {
mounted() {
const editor = new Jodit('#editor')
editor.value = '<p>start</p>'
},
}
demo

TypeError: _vm.moment is not a function in Vuejs

I have a problem migrating to moment on Vuejs.
After running npm install vue-moment and adding to my script:
<script>
const moment = require('vue-moment');
...
</script>
I added this into my <template> :
<h1>{{moment('2017-12-20 11:00').fromNow()}}</h1>
And I get this error:
[Vue warn]: Error in render: "TypeError: _vm.moment is not a function"
You can use it globally as #red-X said, but you can add it only on your component:
import moment from 'moment'
export default {
data: () => ({
moment: moment
})
}
And then you can access it in your HTML template.
But i recommand you to use computed vars for using this kind of code, and to not have logic in your html template, just render computed vars inside your templates for readability.
And with this solution, you don't need to have moment library available globally or in your component, just the import.
Here it's an example :
import moment from 'moment'
export default {
computed: {
distanceFromNow() {
return moment('2017-12-20 11:00').fromNow()
}
}
}
And in your template :
<template>
<div>
{{ distanceFromNow }}
</div>
</template>
import * as momentTemp from 'moment';
const moment = momentTemp["default"];
Did you add the 'moment' attribute to the lifecycle 'methods',forExample:
methods:{
moment,
function a(){},
}
Did you add moment to the global Vue object like this:
const moment = require('vue-moment');
Vue.use(moment)
Just adding it to the local scope of a component will not make it available for use in the template. Everything referenced in the template is taken from the component itself.

Vue dynamic components - watch for mounted

I'm using Webpack dynamic imports and Vue dynamic components to lazy-load a rather large Vue markdown-parsing component.
Now, I want to add syntax highlighting with Prism.js. I'm currently using the mounted() lifecycle hook of the parent component to install syntax highlighting, but this is only working some of the time, since the syntax highlighting depends on the Markdown component to be loaded first (when I manually execute Prism.highlightAll() from the console after page load, it works every time).
Relevant source code:
<template>
<vue-markdown>
# Hello
```javascript
import { hello } from "world"
```
</vue-markdown>
</template>
<script>
export default {
components: {
"vue-markdown": () => import("vue-markdown/src/VueMarkdown"),
},
mounted() {
import("prismjs/themes/prism-tomorrow.css")
.then(() => import("prismjs").then(p => Prism.highlightAll()))
}
}
</script>
So how do I wait for a dynamic component to load? I almost want something like this:
<vue-markdown v-on:mounted="syntaxHighlighting()"></vue-markdown>
I solved the problem by creating my own component which extends the VueMarkdown component, but with a mounted() hook that activates syntax highlighting. It looks like this:
<script>
import VueMarkdown from "vue-markdown/src/VueMarkdown"
import "prismjs/themes/prism-tomorrow.css"
import Prism from "prismjs"
export default {
extends: VueMarkdown,
mounted() {
Prism.highlightAll()
}
}
</script>
Then, I dynamically import this component into the parent component.
Not sure if this is the best solution, though...

How to create a reusable component in VueJs?

I would like to create Side Panel as a reusable component in Framework7 with VueJS. Here is my code..
Card.vue
<f7-card>
<f7-card-header>Card header content</f7-card-header>
<f7-card-content><img src="https://wiki.videolan.org/images/Ubuntu-logo.png"></img></f7-card-content>
<f7-card-footer>Card footer content</f7-card-footer>
</f7-card>
Now i registered as a component like below,
import Vue from 'vue'
export default [
{
path: '/card/',
component: require('./Card')
},
]
In later vues i imported as,
import Card from './Card.vue'
and i try to access in another vues like,
Now i'm getting an error like
[Vue warn]: Unknown custom element: - did you register the
component correctly? For recursive components, make sure to provide
the "name" option.
Can anyone help me where have i mistaken?
Thanks,
It's not really clear from your code exactly what you are doing, but the error you are getting happens when you try to use a component as a child of another component without registering it in the parent's components setting like this:
<script>
import Card from './Card.vue'
export default {
data () {
return {
somedata: 'some value'
}
},
components: {Card: Card}, // <- you're missing this
// etc...
}
</script>
You can also register components globally. More here: https://v2.vuejs.org/v2/guide/components.html#Local-Registration
Are you showing us all of Card.vue? For a valid single-file vue component, I would expect to see <template>, <script> and <style> elements. The render function will be generated from whatever you put in the <template> element.
Make sure that the component that you want to reuse is wrapped inside a template tag
As follows
<template>
<div>
<component data/>
<div/>
<template/>
Then register it inside the parent
Like so
export default {
name: "Card",
components: {
Card
},
};