Can Vue.js components and traditional Vue instances be utilized concurrently within an application?

Currently, my Laravel application utilizes Vue.js as the frontend JavaScript framework. While I employ components for large scripts, I prefer using a Vue instance in the blade template for smaller scripts.

The issue arises with my app.js configuration - favoring one method breaks the other and vice versa.

require('./bootstrap');

window.Vue = require('vue');


Vue.component('repairs', require('./components/repairs.vue'));
Vue.component('repair-show', require('./components/repair-show.vue'));

const app = new Vue({
    el: '#app'
});

This code snippet works well with components, while the one below excels at creating an instance:

require('./bootstrap');

window.Vue = require('vue');


Vue.component('repairs', require('./components/repairs.vue'));
Vue.component('repair-show', require('./components/repair-show.vue'));

I understand the challenge stemming from exporting components to the global Vue instance; however, I am curious if there exists an alternate configuration that enables both methods to function seamlessly.

To provide context, here is a sample of a Vue script within a Vue component:

import axios from 'axios';

var csrf_token = $('meta[name="csrf-token"]').attr('content');

export default {

    created() {
        this.blocks = JSON.parse(this.b);
        this.contractors = JSON.parse(this.c);
        this.token = csrf_token;
    },
    props: ['b', 'c'],
    
    data(){

        return {

          blocks: '',
          blockSelected: '',
          units: '',
          token: '',

        }
    },

    methods: {
      getUnits: function(){

        var self = this;

        axios.post('/getrepairsUnit', {
                blockSelected: this.blockSelected,

            })
            .then(function(response) {

                self.units = response.data;

            })
            .catch(function(error) {
                console.log(error);
            });

      },
    }
}

Additionally, here is an example of my Vue instance...


  <script>
  var app = new Vue({
    el: '#app',
    data: {
      deposit: 0
    }
  });
  </script>

When attempting to run the Vue instance, I encounter this error message:

[Vue warn]: Property or method "deposit" is not defined on the instance but referenced during render. Ensure you declare reactive data properties in the data option.
(found in root instance)

Although I can log output successfully, the view does not capture the data. This issue seems to resolve when I remove the global instance from the app.js file.

Thank you

Answer №1

To avoid conflicts, it is important to remember that a single page element cannot have two Vue instances running simultaneously. If you require multiple Vue instances on the same page, consider creating separate JavaScript bundles for each instance. Alternatively, you can include a Vue instance directly in the blade template and omit the inclusion of the app.js file.

Answer №2

Vuejs requires at least one instance to be created and bound to an ID, like so:

require('./bootstrap');

window.Vue = require('vue');


Vue.component('repairs', require('./components/repairs.vue'));
Vue.component('repair-show', require('./components/repair-show.vue'));

const app = new Vue({
    el: '#app'
});

In the code above,

const app = new Vue({
        el: '#app'
    });

is considered the core of a Vuejs application. This is where your vuejs application starts bootstrapping.

Make sure to follow this structure while working with Vuejs.

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

Error: The strategy for authentication is not recognized as "login" - Express and Passport

I am currently experimenting with a basic MEAN stack tutorial I found online. The technologies involved are: Node.js Express.js Passport.js Below is the code snippet for the application file: app.js var express = require("express"); var mongoose = req ...

The javascript file does not load and stringByEvaluatingJavaScriptFromString is also not running?

In my application, I am downloading an HTML file from the server and displaying it in a uiwebview. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths firstObject]; NSStri ...

Invoking a PHP class through an AJAX response handler code

I'm attempting to access a PHP-File using AJAX. When I use a basic PHP-File like this: <?php header('Content-Type: text/html; charset=utf-8'); header('Cache-Control: must-revalidate, pre-check=0, no-store, no-cache, max-age=0, pos ...

Struggling with the task of assigning a glTF item to a separate layer within Three.js

Exploring the use of layers in Three.js. This script includes a sphere, a triangle, and a glTF object (car). I activated a second layer: camera.layers.enable(1); Assigned the sphere, triangle, and glTF object to layer 1: car.layers.set( 1 ); sphere.lay ...

Struggling to combine select dropdown choices in one calculation

​​I'm currently working on a project where I need to create a website that multiplies three numbers selected from dropdown menus together. However, when I attempt to perform the calculation, I only get the result "1" displayed. I've spent sev ...

Is There a Lack of 'Contains' Support in JavaScript's ScriptEngine?

Below is some code that I am working with. ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); engine.eval("[1, 2, 3].contains(1)"); However, when I run the code, it throws the following e ...

Is there a way in AngularJS to set all radio buttons to false when one is chosen as true?

When I retrieve true/false string values from the database, I am unable to alter the data. The example I provided is simply a representation of the string values true or false that I receive from the database. My goal is to have a single radio button disp ...

Transfer results of SQL query from PHP to JavaScript array

Every day, I manually update a JavaScript variable in the following way: <script> var data = [ ['Austria','IBM','8284927','UF93NV', '10'], ['Spain','Dell&ap ...

Designs for an HTML5 Cheeseburger navigation interface

I've been struggling to implement a functional and visually appealing hamburger menu on my website. The challenge lies in integrating the menu seamlessly into the page rather than having it just pop up abruptly. Despite trying various webkit tools, I ...

Error Encountered: The validate function is missing in the wrapper.vm.$refs.editForm object in Jest unit tests

I am facing difficulty while trying to write a test case for form submission. The error message "wrapper.vm.$refs.editForm.validate is not a function" is causing issues and I can't seem to figure out the problem. Can someone please help me with this? ...

The Angular service/value is failing to retrieve the updated variable from the $(document).ready() function

Currently, I'm facing an issue with my Angular service/value. It seems to be grabbing the original variable instead of the new one that is supposed to be inside $(document).ready(). Here's the relevant code snippet: var app = angular.module("app ...

Learn how to properly convert a string into a valid URL using the Next JS router when pushing pages

I'm dealing with a string that looks like this: /dashboard/products/:id. My goal is to utilize Next Js's router to navigate to that URL and replace the placeholder :id with an actual id. Here's the code I've written: {products.map(prod ...

Maintaining the functionality of an AJAX web page even after extended periods of inactivity

When using my one-page web app, I sometimes leave the page open overnight and find that when I come back in the morning, things don't work as they should. It seems like Javascript is acting up - edit-in-place loads incorrect data, ajax calls fail to f ...

What is the best way to pass an array as a parameter in Angular?

I have set up my routing module like this: const routes: Routes = [ { path: "engineering/:branches", component: BranchesTabsComponent }, { path: "humanities/:branches", component: BranchesTabsComponent }, ]; In the main-contin ...

How to prevent selecting a particular date in React-datepicker?

Hey there, I'm new to Stack Overflow and I'm facing a challenge that I hope someone can help me with. I'm currently working on a project where the previous developers used a React datepicker. The project managers want to keep it, but I need ...

What is the proper way to select this checkbox using Capybara in Ruby?

Is there a way to successfully check this checkbox?view image description I attempted the following: within('div[id="modalPersistEtapa"]') do element = @driver.find_element(:xpath, '//*[@id="2018_4"]/ ...

JQuery not being recognized by MVC4 view

I encountered an issue with my @Html.DropDownList that is supposed to invoke a jquery function, but it seems that the function is not being called. I've attempted the following: $(document).ready(function () { $('.test').change(function ...

JavaScript Ping Pong Challenge

I'm currently investigating why the browser returns NaN for the Positions. The game is being rendered in a loop and updated as soon as the monitor is ready, which is defined in the update() function and runs infinitely. The reset() function is a part ...

Transforming jQuery Object into a String after making an AJAX request

If I were to submit a form with some text in the value of user_input, let's say "I am free," through AJAX, and it comes back to me as a string. Once it becomes an Object, how could I convert it back into a string format? Thanks, <!DOCTYPE HTML> ...

building CharFields dynamically in Django

I am looking to gather input from the user using CharField. Using the value entered in CharField, I want to generate the same number of CharFields on the same page. For example, if the user enters "3" and clicks OK, it should display "3" CharFields below ...