Vue instance inside another Vue instance - vue.js

I’m integrating Vue with a CMS called AEM thats works basically as component base system like Vue works too. But instead of having a webpack and imports of .vue files, every component on this CMS is a new Vue instance (new Vue({…})). So on my page I have a lot of Veu instances that communicate with each other using the same store (vuex).
This is actually working fine, but I have a scenario when I need a CMS component inside another. Since both this components are a unique vue instance and the “el” property from the parent includes the “el” from the child, the child component doesn’t work.
I know that this is not the expected use of this lib, but is there any way that I can tell or share the same “context” on both vue instances or even another approach for this scenario.
Thx,
Alexandre.

There should be only one instance of Vue.
I suggest you to create single empty Vue instance inside the body tag
All your existent Vue instances transform into components
Register all components in the root Vue instance
With this approach it will be fine to nest one component into another

You should use only one Vue instance as #shrpne mentioned.
If you keep instantiating Vue instances for every component, you'll run into issues while debugging or with component communication and overall this becomes very missy and you miss out on parent-child communication and inheritance provided by Vue.
I don't know about your Vue architecture, but I am currently working on a manual for working with Vue in AEM.
The basic premise is to use Vue's inline-template and vanilla-js, No typescript, nodeJS build, jsx or anything else at build time, just vanilla-js so that when your page is loaded and even before your js bundle is present, the DOM is already there, you just need to mount components by instantiating one Vue instance that will mount all components. This is also great for SEO (unless you plan to server-side render Vue components in java... which is possible theoretically, but good luck!)
Here is a sample AEM/Vue component:
<simple-counter inline-template>
<button v-bind:style="style" v-on:click="add">${properties.clicksText || 'clicks: '} {{ counter }}</button>
</simple-counter>
the JS:
notice how it does not have a template in the JS, because it's inlined above
Vue.component('simple-counter', {
data: function() {
return {
counter: 0,
style: {
color: 'red',
width: '200px'
}
}
},
methods: {
add: function() {
this.counter = this.counter + 1;
this.style.color = this.style.color == 'red' ? 'green' : 'red';
}
}
})
You can build more AEM components in this fashion, then at the end of your clientlib when all your Vue components have been registered, you can run:
new Vue({ el: '#app'})
This, off course, assumes that your page body or some other parent element has the id: app.
The second part of this, how do you enable re-mount of components after authoring dialog is submitted, you could just refresh the page.
I have a question about how we can re-mount components without refreshing the page here
The basic idea is to add an afteredit event to the component and run a new Vue instance only on the newly mutated component... still working on that

Solution:
Replace all new Vue(...) stuff into Vue.component(...) Vue.extend(...) etc for better interface management.
Only use ONE Vue instance witch is new Vue({...options})
Slice your vuex store into modules.
Google teacher knows everything.

Related

Automatically initialising multiple Vue.js3 Single File Components each within its own Vue instance

I'd like to have multiple Vue3 components. Each as a separate Vue instance, and all automatically loaded.
Why? Because I want to use them on a page where there's potentially many other JS scripts that alter the page so I cannot change the DOM for them (by globally initialising Vue) and I want not to worry that they will mess with my Vue components - so mounting all my components to some one big Vue instance like <body id="app"> is not an option.
With Vue2 it was a bit easier but does not work with Vue3. Now after some fight I worked out a solution for Vue3 it works fine but it seems ugly in my eyes so I assume there's a better one :)
I'm using (laravel-mix - Webpack solution for building my files).
Here's my HTML file with the components embedded:
// index.php
<TestOne data-vue-component="TestOne" />
<TestTwo data-vue-component="TestTwo" />
<TestOne data-vue-component="TestOne" />
And here's my JS file for loading those components:
// index.js
import { createApp } from 'vue';
const vueComponents = document.querySelectorAll('[data-vue-component]');
if (vueComponents.length) {
vueComponents.forEach((elem) => {
const componentName = elem.getAttribute('data-vue-component');
const app = createApp(require(`./components/${componentName}/${componentName}.vue`).default);
app.mount(elem);
}
}
So I look for the Vue components using data attribute data-vue-component and then for each one found I get the component's name, create a Vue3 instance importing the component at the same moment. Finally I mount it and do the same with the next one.

Exposing functions on a Vue-defined Web Component (Custom Element)

Per the Vue docs, it's possible to build components in Vue (v3) and package them as native Web Components for use with any framework or none at all.
As I've already found, the gap between design models for Vue components and Web Components can make this complex and sometimes a straight-up bad idea (at what point is it better and more maintainable to just go ahead building fully-native components?)... But let's assume for a moment that it's necessary here.
My question - What's the best way to expose a function-like interface on a Vue-built Web Component (to parent nodes)?
The Vue doc discusses passing in reactive data via props/slots, and publishing CustomEvents from the components, but I don't see mention of
taking function calls (or at a stretch, events) from outside. As far as I can tell this is a pretty strong assumption that data and event flow on the rest of the app/page works in a very "Vue-like way"?
For now, my workaround on this is to look up the host element in onMounted() (as per this question) and just set whatever extra properties are required at that point (hoping they shouldn't be required before the Vue component mounts, because I'm not aware of any external events raised when Vue finishes mounting the custom element).
This way the function can still be defined in the context of, and access variables/etc from, the setup function - but can be called by other elements on the page that only have a reference to the element, not the Vue component.
Can't say I like it much though:
<template>
<div ref="someElInTemplate">...</div>
</template>
<script lang="ts">
interface MyCoolHTMLElement extends HTMLElement {
myCoolFunction: () => void;
}
</script>
<script setup lang="ts">
const someElInTemplate = ref<HTMLElement>();
function myCoolFunction() { }
onMounted(() => {
const hostNode = (
somElInTemplate.value?.getRootNode() as ShadowRoot | undefined
)?.host as MyCoolHTMLElement;
hostNode.myCoolFunction = myCoolFunction;
});
</script>

Vue 3: Composition API with external templates

So, I come from Angular world where by default we are separating view from business logic... and I don't like single file components, especially when they are getting bigger and convoluted.
Before in vue 2, I would have myComponent.vue with script tag and have it like so:
<template src="./myComponent.html"></template>
To call the view file... and it would work... all the methods were accessible
but now, if I use the setup way
<script setup lang="ts">
const suggets = () => {
}
</script>
<template src="./myComponent.html"></template>
I would get a typescript error that suggest was declared and never used...
Also for example:
<carbon-search /> component would not work
Failed to resolve component: carbon-search If this is a native custom
element, make sure to exclude it from component resolution via
compilerOptions.isCustomElement.
Any good and elegant way to split the component view and business logic (and css)?

How add simple Jquery and <script> in VueJS?

I has simple <script> connect and jquery on page. Here is example: https://codepen.io/TidioSupport/pen/WNePeao
How i can add it correctly to my Vue component?
Because when i try add it, i received: Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed. or component not loading.
Hope for your help, thanks!
You should add it in the head of the html where you are calling your vue app
In your mounted lifecycle of Vuejs, you can append the script and then use its function.
Your variables for those scripts can be accessible by window global object.
mounted() {
let chatScript = document.createElement('script')
chatScript.setAttribute('src', 'https://code.tidio.co/fouwfr0cnygz4sj8kttyv0cz1rpaayva.js')
document.head.appendChild(chatScript)
}

Is it component definition in vue? How do I find whether it is a component by looking at the code?

When I search for something I came across this post
Here, something, I believe it is component, is defined as below.
export default {
name: 'app',
methods: {
testFunction: function (event) {
console.log('test clicked')
}
},
components: {
Test
}
}
As per the documentation, I came across this
import BaseButton from './BaseButton.vue'
import BaseIcon from './BaseIcon.vue'
import BaseInput from './BaseInput.vue'
export default {
components: {
BaseButton,
BaseIcon,
BaseInput
}
}
I really not sure, whether app is a component which contains Test. Is it the component definition in export? How do we understand that is a component from vue code?
Is it only by the below ways?
Vue.component
components in Vue instance
Not sure - the export default way?
I understand that I sound different because it is Javascript. Could someone help me with this?
There are conventionally, three different types of components in Vue JS.
Root Component
View Component
Normal Component
In a conventional structure the Root component is named 'app' and is passed to the Vue instance when initializing the App for the first time. This component can not be imported and reused inside other components as it will cause a recursive effect. For example this App.vue file is a Root component. It is used inside this main.js file and passed to the Vue instance using new Vue.
The View components are dynamically added or removed from the Root component based on the route. They are written and act as normal component and are only used for Vue router component property. For example the Home and Comments components inside this Router index file are known as View components. They are passed inside the route objects as components inside individual routes. When the app navigates to that particular route, the <router-view> template inside the App.vue file gets replace with the template of the corresponding View component.
Normal components can be used anywhere and are imported by other components. They can be imported inside the View components as well as the Root components. For example, in root component App.vue we see the component Navbar is used. In View component Comments.vue the Replies component is used.
All these components are identical in declaration and behavior but differ in usage.