Discover various ways to encapsulate Vue.js components

I am currently in the process of developing a website that utilizes classic multiple pages powered by blade templates. However, I am looking to incorporate vuejs2 components for more dynamic functionalities.

Although things are running smoothly, I am facing a challenge when it comes to declaring containers parsed by VueJs for these components.

I have a need for using numerous components in various locations, but I am unable to designate a large main container as the VueJs container due to conflicts with <script> tags. Whenever I attempt this, I encounter errors such as:

- 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.

My current approach in my app.js file is as follows:

new Vue({
  el: '#need-components-1'
});
new Vue({
  el: '#need-components-2'
});
new Vue({
  el: '#need-components-3'
});

However, I find this method quite unfavorable. I would prefer to either declare the entire content as VueJs-friendly or utilize a common class or attribute for containers. As of now, I have to assign a new id each time I want to integrate components into a different location. Additionally, VueJs logs console errors for elements that are not always loaded, which can be frustrating.

Is there a more elegant and convenient solution to tackle this issue?

Thank you.

Answer №1

One way to indicate that an element is a root Vue is by using a specific identifier. Upon page load, you can loop through the elements on the page and initialize Vue instances for each of them.

For example:

console.clear()

const vues = document.querySelectorAll("[data-vue]")
for (let v of vues)
  new Vue({el: v, data: {message: "Hello from Vue"}})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div data-vue="true">
   <h2>{{message}}</h2>
</div>
<h4>Some other page content</h4>
<div data-vue="true">
  <h2>{{message}}</h2>
</div>
<h4>Some other page content</h4>
<div data-vue="true">
    <h2>{{message}}</h2>
</div>

It's important to ensure that the correct data is associated with each Vue instance if they differ between instances.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In angular.js, repeating elements must be unique and duplicates are not permitted

My view controller includes this code snippet for fetching data from an API server: $scope.recent_news_posts = localStorageService.get('recent_news_posts') || []; $http({method: 'GET', url: 'http://myapi.com/posts'} ...

Encountering error: Unknown flag '-p' when trying to execute yarn build:prod in Angular 6

For the past two days, I have been encountering a problem. After updating Angular from version 4 to 6, I am unable to generate a production build. Commands like yarn build and yarn dev are functioning properly. However, when I execute yarn build:prod, I re ...

Demonstration of Concurrent Page Processing in Flask

Currently, I am working on an application that heavily utilizes graphics using libraries such as Raphael and graphdracula. The main functionality of the application involves drawing various graphs across different pages named graph1, graph2, and graph3. L ...

Is it advisable to incorporate Material-UI into a React project?

When it comes to designing a login page in react, I stumbled upon material-ui. The real question is, should we utilize Material-UI for this purpose? Furthermore, how can we manage styles in a separate file in the given examples? It seems logical to place t ...

Every time I attempt to submit the login form on the Ionic and Angular page, instead of capturing the values of the form group, the page simply refreshes

Struggling with submitting the login form in Ionic and Angular? When attempting to submit, the page reloads instead of capturing the form group values. I am utilizing angular reactive forms and form builder within the ionic framework. Need assistance in id ...

The for loop does not pause for asynchronous code to complete

The for loop in my code has a function call that contains async code. However, the issue is that the for loop does not wait for the async code to return before continuing with the iterations. The function aFunctionThatRunsAsync is from a library that I ca ...

IntelliJ has removed the connect-flash plugin, preventing me from reinstalling it

Learning node.js is new to me and I encountered a strange issue. While working on implementing login functionality with passportjs, I faced an error where req.flash() was not functioning properly. Oddly enough, it was working fine yesterday when I used it ...

What is the significance of AngularJS in crafting Single Page Applications?

My introduction to AngularJS was discovering its perfection for Single Page Applications (SPAs). I'm intrigued by what this means and eager to learn more about it. Can someone explain the significance of SPAs in relation to AngularJS? ...

What is the best way to retrieve every single element stored in an Object?

On a particular page, users can view the detailed information of their loans. I have implemented a decorator that retrieves values using the get() method. Specifically, there is a section for partial repayments which displays individual payment items, as d ...

What is causing my Bootstrap Controls to malfunction?

I'm trying to create a Bootstrap carousel that shows 3 items at once and includes controls to switch between them. The carousel I've made does display the three items, but for some reason, the controls are not responding when clicked. I'm un ...

Issue encountered with @Nuxt.js/Cloudinary plugin for Media Enhancement: "Access to this endpoint is restricted due to insufficient permissions"

I am currently utilizing the @nuxtjs/cloudinary module based on the module guide and a course video. However, I am encountering an error in the response as follows: Status 403, message: You don't have sufficient permissions to access this endpoint&qu ...

Starting data initialization using a property object within a Vue component

I am encountering an issue with two Vue components, EventTask and EventCard. Within EventTask, there is a currentEvent object in the data section, which I pass as a prop to EventCard using the following code snippet: <event-card :current-event="cur ...

Error: Unable to locate font in the VueJS build

Within my config/index.js file, I have the following setup: ... build: { index: path.resolve(__dirname, 'dist/client.html'), assetsRoot: path.resolve(__dirname, 'dist'), assetsSubDirectory: 'static', assetsPub ...

What causes req.body to be null after using event.preventDefault() in conjunction with fetch api, express, and node.js?

Is there a way to submit a form without causing the page to reload and still retrieve an object from MongoDB using server side scripts? I've tried preventing the default behavior of the form with an event handler to avoid the page refresh, but this ca ...

Instructions for incorporating a personalized document in NextJs version 13

In order to enhance the design of my upcoming Next.js 13 project, I am looking to integrate a custom design system package. This particular package necessitates the creation of custom documents within the page directory, as outlined in the official Next. ...

How to manipulate iframe elements using jQuery or JavaScript

Hey there, I have a simple task at hand: I have a webpage running in an iFrame (located in the same folder on my local machine - no need to run it from a server) I am looking to use JavaScript to access elements within this iFrame from the main page. How ...

Solving the CORS issue with Vue, Axios, and the Google Maps Place API

After reviewing the other responses, it seems that my question remains unanswered. Environment NodeJS 12.19.0 VueJS 2.6.10 Axios 0.15.3 Current Axios configuration: axios.defaults.headers.common['Authorization'] = store.apiKey axios.defaults.he ...

Ways to retrieve the value of a specific key within an object nested within another object

Suppose I have a variable named x with the following structure: x = { choice1: { choice: { name: "choice1", text: "abc", key: "key1" } isChecked: true }, choice2: { choice: { name ...

With Vue 3 Pinia, values fetched from an API within a Pinia store cannot be statically assigned; they will always be reactive

I have a frontend built with vue3 and using pinia as the store. I am setting it up as shown below: export const useShopStore = defineStore( "shop", () => { const state = reactive({ data: { fruits: [], owners: [] ...

Adjust the size of an Angular component or directive based on the variable being passed in

I'm looking to customize the size of my spinner when loading data. Is it possible to have predefined sizes for the spinner? For example: <spinner small> would create a 50px x 50px spinner <spinner large> would create a 300px x 300p ...