How to Access Vue-Loader Components in an HTML File - vue.js

I would like to use the modular style and file format of Vue Loader (i.e., where I have a template section, script section and style section in each .vue file).
What I can't figure out how to do (or if it is even possible to do) is use my custom templates in an html file.
For instance, in the App.vue file I can use the following code:
<template>
<div id="app">
<message>Hello there</message>
</div>
</template>
This will work to display a custom message component on the home page.
What I would like to do instead is use my custom components in html files. For instance, in the index.html file to use the following code:
<div id="app">
<message>Hello there</message>
</div>
Any idea how I can do this? Thanks.
NOTE: I am new to Vue Loader and semi-new to Vue (so I apologize in advance if the answer to this question is obvious).

There are many ways you can compile a single file component and then use that component in a web page.
Use vue-cli
Vue released a command line interface tool called vue-cli that can initialize projects and build components with zero configuration. One option to build a component that you can use in your page is to use vue build.
vue build MyComponent.vue --prod --lib MyComponent
This will compile a script that exposes MyComponent. If you include that script in your page and then add it globally,
Vue.component(MyComponent)
That component will be available to you in any of your Vues.
Make a plugin
Here is a sample of a very basic framework for making a plugin.
myPluginDefinition.js
window.MyPlugin= {};
MyPlugin.install = function (Vue) {
Vue.component('my-component', require('./my-component.vue'));
}
webpack.config.js
module.exports = {
entry: "./myPluginDefinition.js",
output: {
path: __dirname+'/dist',
filename: "MyPlugin.js"
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue-loader',
}
]
}
};
This will build a file called MyPlugin.js that will contain each of the single file components that you include in the install function. Include the script on your page and then call
Vue.use(MyPlugin)
and you will have all of your components.
Use a custom webpack configuration
There are many ways you could configure webpack to build your single file components. You could build them all into a single file or build them separately. I suggest if you want to use one of these options you ask a separate question.

Actually you can do this easily by:
register your component :
Vue.component('message', {
template: '<div>A custom component!</div>'
});
then comment the render function in your Vue instance like so:
new Vue({
el: '#app',
// render: h => h(App)
})
after that you will be able to render your message Tag like this:
<div id="app">
<message></message>
</div>
Edit :
if you don't want to use this way you can define it in your view instance:
new Vue({
el: '#app',
// render: h => h(App)
components: {
message: {
template: `
<h1>Hello World</h1>
`
}
}
})

Import desired component definition object and pass it to options.components
<template>
<some-component></some-component>
</template>
<style>...</style>
<script>
import SomeComponent from 'path/to/some-component.vue';
export default {
components: {
// ES2015 shorthand for SomeComponent: SomeComponent
SomeComponent
}
}
</script>
That leverages local component registration
Both the default export and SomeComponent are component definition objects.

Related

How to compile vue3 SFC component .ce.vue into .js

I am looking for a way to compile a "single-file component" (.vue or .ce.vue extension) with console tools into a js. the project is made with yii2. here is what i tried:
Following this guide i managed to define a custom element (without SFC .vue):
import { defineCustomElement } from 'vue'
const MyVueElement = defineCustomElement({
// normal Vue component options here
props: {},
emits: {},
template: `...`,
// defineCustomElement only: CSS to be injected into shadow root
styles: [`/* inlined css */`]
})
// Register the custom element.
// After registration, all `<my-vue-element>` tags
// on the page will be upgraded.
customElements.define('my-vue-element', MyVueElement)
this guide mentions "Using Vue SFC as Custom Elements", but i have no clue how to run it, as well as this #vue/compiler-sfc.
using the library built with vitejs in library mode makes my (php) app throw
Uncaught TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".
so what is the best way to build a SFC
MyTest.ce.vue
<template>
<div>
hello world
</div>
</template>
<script>
export default {
tag: 'my-test',
name: 'MyTest',
data() {
return { count: 0 }
},
};
</script>
<style scoped>
div {
font-size: 200%;
}
</style>
into a .js that i can load in my app, preferably with a single command line tool, without webpack or similar?

VUE Web component inside legacy app results in error "_Ctor, object is not extensible"

I'm having trouble importing my custom component in my legacy app.
I pre-compiled my SFC as a webcomponent with vue-cli builder, and I import inside my main.js file this way :
import * as HelloWorld from '../dist/hello-world.js'
Vue.component('hello-world',HelloWorld); //if I add my component globally (same _Ctor error)
Then I load my app on a container div :
var app = new Vue({
el:"#container",
data: {
test: 'Vue is init !' //just a test to validate init
},
components:{
HelloWorld //my web component locally (same _Ctor error)
}
});
When my app load, I get this JS error...
I noticed that when the page is loaded without the following component tag :
<hello-world></hello-world>
no error is thrown and if I add the component tag through JS after the page is loaded, component is properly working.
If I add this component outside of my Vue.el (#container) scope, it's working too.
However, I would like to add this component to #container.
I import Vue 2 through CDN.
Seems like a loading or building error but I can't get it.
Thanks for your help.
hello-world.js is a precompiled .VUE file with vue-cli, just a test file catching some events :
<template>
<h1 v-on:click="clickon"
v-on:mouseenter="addone"
>{{msg}}</h1>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
msg: 'Hello world!'
}
},
methods : {
clickon: function () {
// `this` inside methods points to the Vue instance
alert('Clicked')
},
addone: function(){
this.msg = 'Mouse entered'
},
}
}
</script>
<style>
h1{
color:red;
}
</style>
Precompiled with :
vue build --target wc HelloWorld.vue
Got it working by building it with --target lib and importing my JS file with:
import '../dist/HelloWorld.umd.js';
Then it can be added to my Vue instance with:
components:{
"hello-world":HelloWorld
}
Seems to be the right way to do it; web components can't be imported this way.

defining global variables with vite development

Now I am using vite build tool for my vue SFC app. I read the documentation of vite with the link below:
vite config link
If I am not wrong, the define option in config could be used for defining global constants. What I want to do is to define for example the name of my App in a variable inside this option and then use it in my Vue components. But unfortunately there is no example of code in the documentation about this option.
I tried this code in my vite.config.js file:
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
define: {
global: {
appName: "my-custom-name"
}
},
plugins: [vue()]
})
I am not sure that the syntax and code is correct! And also if it is correct I don't know how to call (use) this constant in my vue app components (.vue files). For example I want to use it in template or script part of this component:
<template>
<div class="bgNow">
<p class="color1">
{{ use here }}
</p>
</template>
<script>
export default {
data() {
return {
name: use here
};
},
methods: {
nameMethod() {
console.log(use here);
}
} // end of method
} // end of export
</script>
<style scoped></style>
I declared the places that want with "use here" in the code. And also if there is any other way that I could define some global constants and variables in my vite vue app, I very much appreciate your help to tell me about that.
define is a config that tells Vite how to perform a search-and-replace. It can only replace one string for another (objects cannot be used as a replacement).
For example, to replace all instances of appName with "my-custom-name", use the following config. Note JSON.stringify() is used (per the recommendation in the docs) to ensure the literal string replacement is properly quoted.
export default defineConfig({
define: {
appName: JSON.stringify('my-custom-name')
}
})
If App.vue contained:
<script setup>
console.log('appName', appName)
</script>
It would be transformed to:
<script setup>
console.log("appName", "my-custom-name")
</script>
demo

How to add name attribute in vue component with an error?

I get an error on the screenshot.
How can I provide the name attribute on this code in my app.js?
app.js
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
Vue.component('table-logs', require('./components/TableLogs.vue').default);
const app = new Vue({
el: '#app'
});
TableLogs.vue
<template>
<vuetable ref="vuetable"
api-url="https://vuetable.ratiw.net/api/users"
:fields="['name', 'nickname', 'email', 'gender']"
data-path=""
pagination-path="">
</vuetable>
</template>
<script>
import Vuetable from 'vuetable-2'
export default {
components: {
Vuetable
}
}
</script>
Provide the "name" attribute in your component.
`
import Vuetable from 'vuetable-2'
export default {
name: 'myTestComponent',
components: {
Vuetable
}
}
`
I'm not familiar with how Laravel and Vue work together but in a typical Vue CLI generated project, you add your root component using a render function. For example
<div id="app"></div>
// app.js
require('./bootstrap'); // I imagine this is required
import TableLogs from './components/TableLogs.vue'
new Vue({
render: h => h(TableLogs),
}).$mount('#app')

Message Vue is not defined

I'm new to studying vue so my question may be kind of silly, but why am I getting the message "vue is not defined"? in this code:
<template>
<div id="app">
<input></input>
<button>{{ textoBotao }}</button>
</div>
</template>
<script>
new Vue({
data: {
a: 1
},
created: function () {
console.log('a é: ' + this.a)
}
})
export default ({
data() {
return{
textoBotao: 'Clique aqui'
}
}
})
</script>
In your code, you don't need to create another instance of Vue. I can't imagine a situation where you need to create a new Vue instance in a single file component. Uou can use components if you need to encapsulate some functionality
If you do need to do this, you can use the following code:
import Vue from 'vue'
new Vue({
...
})
please see vue's official documentation and sample projects
Old question, but if someone needs it
If you have new Vue({}) in a js file and you load that js file before loading vuejs javascript file, you will get this error. This was the reason for my error.
Basically add /vue.min.js"> before you add other js files using vuejs
Hope it helps
I think You miss to add vue.js file, example:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.18/vue.min.js"></script>