Vue2: how to register a component from a compiled single file component? - javascript

I am new to Vue2 and Single-File Components.
I have some complex components that I have compiled via Rollup
e.g.
/src/components/a.vue
<template>
....
</template>
<script>
export default {
...
}
</script>
/src/components/b.vue
<template>
...
<ComponentA/>
....
</template>
<script>
import ComponentA from './a'
export default {
...
components: {
...,
ComponentA,
...
},
...
}
</script>
/src/index.js
import ComponentA from './components/a'
import ComponentB from './components/b'
var myMod = {}
myMod.ComponentA = ComponentA;
myMod.ComponentB = ComponentB;
window.myMod = my.Mod
which together ends up in build/main.js and I source into my project.
My project is not a full view app.
If I want to use either ComponentA or ComponentB in my app, do I always need to do:
var foo = 10;
var compBInstance = new Vue({
el: '#this-comp-b-instance',
components: {myMod.ComponentB},
data: function() {
// data defined outside of this
foo: foo
},
template: `<ComponentB :foo='foo'/>`
})
or is there a way for me to be able to just write <ComponentB :foo='10'/>

Related

Dynamically create a component in Vue JS

I need to create a component in Vue JS dynamically on click and then route to that component. I am using Vue 3. Everything needs to happen in one click.
My code looks something like this
methods:{
routerClick(value){
console.log("number is "+value)
this.$router.push({path:'New', name:'New', component: ()=>Vue.component('New')})
}
},
I do not need to move a component that is already created. I want to create a component inside this method and then route to the component using this router. Please, any suggestions will be highly appreciated.
Below is a simplistic solution that works (I'm not an expert in Vue 3).
The main point is to use addRoute before pushing to it, because you cannot specify the route component when pushing to a route.
Here is the codesandbox with the working solution.
<template>
<router-link to="/">Home</router-link>
<button #click="createComponent">Create Component</button>
<router-view></router-view>
</template>
<script>
import { getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
export default {
name: "App",
setup() {
const app = getCurrentInstance().appContext.app;
const router = useRouter();
const createComponent = () => {
// Check if the component has been alreadey registered
if (!app.component("NewComponent")) {
app.component("NewComponent", {
name: "NewComponent",
template: `<div>This is a new component</div>`
});
}
const newComponent = app.component("NewComponent");
// Adding a new route to the new component
router.addRoute({ path: "/new", component: newComponent });
router.push("/new");
};
return {
createComponent,
};
},
};
</script>

How to use <component :is=""> in vue 3 script setup

I am using the experimental script setup to create a learn enviroment. I got a selfmade navigation bar with open a single component.
I am having trouble using the <component :is="" /> method. This method is described in the docs under component basics -> dynamic-components
In the Vue 3 Composition API, it works as expected:
<template>
<NavigationBar
#switchTab="changeTab"
:activeTab="tab"
/>
<component :is="tab" />
</template>
<script>
import { ref } from 'vue'
import NavigationBar from './components/NavigationBar.vue'
import TemplateSyntax from './components/TemplateSyntax.vue'
import DataPropsAndMethods from './components/DataPropsAndMethods.vue'
export default {
components: {
NavigationBar,
TemplateSyntax,
DataPropsAndMethods
},
setup () {
const tab = ref('DataPropsAndMethods')
function changeTab (newTab) {
tab.value = newTab
}
return {
changeTab,
tab
}
}
}
</script>
My approach with the script setup fails:
<template>
<NavigationBar
#switchTab="changeTab"
:activeTab="tab"
/>
<component :is="tab" />
</template>
<script setup>
import NavigationBar from './components/NavigationBar.vue'
import TemplateSyntax from './components/TemplateSyntax.vue'
import DataPropsAndMethods from './components/DataPropsAndMethods.vue'
import { ref } from 'vue'
const tab = ref('DataPropsAndMethods')
function changeTab (newTab) {
tab.value = newTab
}
</script>
do you got any idea how to solve this with the script setup method?
It seems with <script setup>, tab needs to reference the component definition itself instead of the component name.
To reference the component definition, which does not need reactivity, use markRaw() before setting tab.value:
<script setup>
import DataPropsAndMethods from './components/DataPropsAndMethods.vue'
import { ref, markRaw } from 'vue'
const tab = ref(null)
changeTab(DataPropsAndMethods)
// newTab: component definition (not a string)
function changeTab (newTab) {
tab.value = markRaw(newTab)
}
</script>
demo 1
If you need to pass the component name to changeTab(), you could use a lookup:
<script setup>
import DataPropsAndMethods from './components/DataPropsAndMethods.vue'
import { ref, markRaw } from 'vue'
const tab = ref(null)
changeTab('DataPropsAndMethods')
// newTab: component name (string)
function changeTab (newTab) {
const lookup = {
DataPropsAndMethods,
/* ...other component definitions */
}
tab.value = markRaw(lookup[newTab])
}
</script>
demo 2
Tested with Vue 3.0.9 setup with Vue CLI 5.0.0-alpha.8

Vue.js - Component is missing template or render function

In Vue 3, I created the following Home component, 2 other components (Foo and Bar), and passed it to vue-router as shown below. The Home component is created using Vue's component function, whereas Foo and Bar components are created using plain objects.
The error that I get:
Component is missing template or render function.
Here, the Home component is causing the problem. Can't we pass the result of component() to a route object for vue-router?
<div id="app">
<ul>
<li><router-link to="/">Home</router-link></li>
<li><router-link to="/foo">Foo</router-link></li>
<li><router-link to="/bar">Bar</router-link></li>
</ul>
<home></home>
<router-view></router-view>
</div>
<script>
const { createRouter, createWebHistory, createWebHashHistory } = VueRouter
const { createApp } = Vue
const app = createApp({})
var Home = app.component('home', {
template: '<div>home</div>',
})
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar },
],
})
app.use(router)
app.mount('#app')
</script>
See the problem in codesandbox.
FOR vue-cli vue 3
render function missed in createApp.
When setting your app by using createApp function you have to include the render function that include App.
in main.js
update to :
FIRST
change the second line in javascript from:-
const { createApp } = Vue
to the following lines:
import { createApp,h } from 'vue'
import App from './App.vue'
SECOND
Change from :-
const app = createApp({})
to:
const app = createApp({
render: ()=>h(App)
});
app.mount("#app")
When app.component(...) is provided a definition object (the 2nd argument), it returns the application instance (in order to allow chaining calls). To get the component definition, omit the definition object and provide only the name:
app.component('home', { /* definition */ })
const Home = app.component('home')
const router = createRouter({
routes: [
{ path: '/', component: Home },
//...
]
})
demo
Make sure you have added <router-view></router-view> in your #app container.
The solution was simple on my side, I created a component that was empty, after filling in the template and a simple text HTML code, it was fixed.
The solution for me was to upgrade node module vue-loader to version 16.8.1.
I had this issue too. It's a timing issue. I added a v-if to create the component when the page is mounted. That fixed it for me.
<review-info
v-if="initDone"
:review-info="reviewInfo"
/>
// script
onMounted(() => {
initDone = true
})
I was extending a Quasar component in Vue 3, and ran into this problem. I solved it by adding the setup: QInput.setup line last in the component options.
<script>
import { defineComponent } from 'vue'
import { QInput } from 'quasar'
const { props } = QInput
export default defineComponent({
props: {
...props,
outlined: {
type: Boolean,
default: true
},
dense: {
type: Boolean,
default: true
},
uppercase: {
type: Boolean,
default: false
}
},
watch: {
modelValue (v) {
this.uppercase && this.$emit('update:modelValue', v.toUpperCase())
}
},
setup: QInput.setup
})
</script>

How to correctly globally register and use Vue Rangedate Picker component?

I am trying to use VueRangedatePicker and I can't seem to figure out how to use this on the template of some other vue component. I am using Webpack.
I have registered the component/plugin on my main.js file like this:
import Vue from 'vue'
import App from './App'
import router from './router'
import { store } from './store/store'
import firebase from './firebase-config'
import vuefire from 'vuefire'
//////////////// HERE
import VueRangedatePicker from 'vue-rangedate-picker' // importing the plugin here
Vue.use(VueRangedatePicker) // using it
Vue.component('VueRangedatePicker', { }) // creating the component globally (if I don't add this line the app complains the component is not registered
////////////////
Vue.config.productionTip = false
let app;
Vue.use(vuefire)
firebase.auth().onAuthStateChanged(function(user){
if (!app) {
/* eslint-disable no-new */
app = new Vue({
el: '#app',
template: '<App/>',
components: { App, VueRangedatePicker },
router,
store,
VueRangedatePicker
})
}
})
Then on my component component_A.vue I am again importing the VueRangedatePicker plugin in the following manner:
<template>
<div>
<vue-rangedate-picker #selected="onDateSelected" i18n="EN" />
</div>
</template>
<script>
import firebase,{ itemRef } from '../firebase-config';
import VueRangedatePicker from 'vue-rangedate-picker'
export default {
firebase() {
return {
items: itemsRef,
}
},
name: 'component_A',
data () {
return {
}
},
created() {
console.log(VueRangedatePicker);
},
methods: {
onDateSelected: function (daterange) {
this.selectedDate = daterange
},
}
</script>
I know the plugin/component is registered because when I log the Vue Rangedate Picker on the console I can see the object
However I am getting the an error message like this
I have read the complete readme.md file on the project's github but I am still puzzled. What is Vue_Daterange_picker? Is it a plugin? Is it a component? Is it a plugin that allows me to build a component? I am quite confused. Can you clarify this for me a little better? How can I make this work?
This is because you have registered the component with an empty name.
In main.js :
Vue.component('DatePicker', VueRangedatePicker)
Then in your component use the component as :
<date-picker></date-picker>

ModalRight is not defined when using import function

I'm using webpack to bundle all my files together, but I'm having issues with trying to import the template component I created with default name, I keep getting ModalRight is not defined.
This is my App.js file that I'm referencing as the entry in the webpack.config.js
import Vue from '../../public-assets/js/vue/vue.js';
import ModalRight from '../../public-assets/js/vue/components/ModalRightSlide.vue';
window.Vue = Vue;
In my base file, I'm trying to call it like so:
var app = new Vue({
el: '#app',
data: {
},
components: {
ModalRight
},
});
I've also tried in another page using Vue.component('modal', ModalRight ); and <modal></modal> in the html, but I just get that error.
This is the ModalRightSlide.vue file
<template>
<div>
foobar
</div>
</template>
<script>
export default {
}
</script>

Categories

Resources