Utilizing Vuex Store in Blade Template | Laravel and Vue.js

I'm trying to figure out how to access a method or variable that is defined in the Vuex 4 store within my Blade file. Currently, I am utilizing a compiled app.js from Vite. While I can easily access the store in Vue.js components, I am curious if it's possible to do so in a Blade file as well. Of course, the Vue.js #app instance must be present.

If I add the following code snippet at the end of my Blade file:

 <script>
    import {useStore} from "vuex";
    import {onMounted, watch, ref, defineComponent} from 'vue'
    
    export default {
        setup() {
            const click = () => {
                store.commit('mutation');
            };
            
            onMounted(() => {
                alert('test');
            });

            const store = useStore();
            
            return {
                store,
                click
            };
        },
    }
</script>

The console throws an error similar to this:

 Unexpected token '{'. Import call expects exactly one argument.

Answer №1

Let's start by setting aside Laravel in this case, as Blade won't be able to handle it.

Blade functions as the backend for rendering in PHP, while Vue is typically used for single-page applications (SPA).

For this specific task, the job falls purely on Vuex 5.0 / Pinia. You can learn more at .

The best practice here is to create a store for each type of data required, just like demonstrated here: https://github.com/puneetxp/the. This allows you to perform direct testing using JavaScript, such as creating a Store specifically for Product data.

import { defineStore, acceptHMRUpdate } from "/js/vue/pinia.js";
export const useProductStore = defineStore({
    id: "Product",
    state: () => ({
        rawItems: [],
    }),
    getters: {
        items: (state) => state.rawItems
    },
    actions: {
        addItem(product) {
            this.rawItems.push(product)
        },
        removeItem(id) {
            this.rawItems = this.rawItems.filter(i => i.id != id);
        },
        editItem(product) {
            this.rawItems = this.rawItems.filter(i => i.id != product.id);
            this.rawItems.push(product);
        },
        upsertItem(products) {
            products.forEach(product => {
                this.rawItems = this.rawItems.filter(i => i.id != product.id);
                this.rawItems.push(product);
            });
        }
    },
})

if (import.meta.hot) {
    import.meta.hot.accept(acceptHMRUpdate(useActive_roleStore, import.meta.hot))
}

You can then utilize this in your component:

import { useProductStore } from "/js/vue/Store/Model/Product.js";
export default {
    template: ``,
    data() {
        return {
            useProductStore,
        }
    }
}

To access the data, simply use `useProductStore().items` following my design, or customize it to fit your needs.

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

Tips for selecting multiple elements with the same class name in Protractor for Angular:1. Use the `element

Snippet of HTML code: <div class="block ng-scope" ng-repeat="skills in data.primary_skills"> <div class="block skillsLineItem" ng-class="{manditorySkillsLineItem:skills.mandatory, skillsLineItem:!skills.mandatory}"> < ...

Tips for extracting data from cells within an HTML table using JavaScript

I am looking to extract the values from a cell of an HTML table in order to store them in a MySQL table using PHP. I prefer to utilize JavaScript instead of jQuery. I have assigned a unique ID to each TR based on the ID field in the MySQL table. Additiona ...

Personalize your message in a JavaScript alert using Bootstrap notifications

On numerous websites, a new visitor landing on the page is greeted with an alert notification that pops up in either the bottom right or left corner. The code below functions perfectly fine, except for my unsuccessful attempts to change the message text w ...

Steps to deactivate a individual v-expansion-header

(I am working with Vue 2.6) - I have been exploring the v-expansion-panels in Vuetify and came across the disabled property in the documentation. However, setting it disables the entire v-expansion-panel, whereas I need to disable individual occurrences ...

Error encountered in thread "main": Issue with parsing string literal

import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class FindElementsUsingJS { static WebDriver driver= new FirefoxDriver(); public static void main(Stri ...

Compatibility of HTML5 websites with Internet Explorer

Following a tutorial on HTML5/CSS3, I meticulously followed each step to create a basic website. While the demo of the site worked perfectly in Internet Explorer 8 during the tutorial, my own version did not display correctly when viewed in IE8. I discove ...

Encountering an issue with the autocomplete feature in the jQuery library where it is stating "this.source is not a function."

Here's the code snippet I'm working with: $.ajax({ type: "GET", url: "https://url.com", dataType: "json", success: function (data) { $("#search").autocomplete({ source: data, select: function (even ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...

Creating distinctive identifiers for individual function parameters in JavaScript using addEventListener

I am working on a for loop that dynamically generates elements within a div. Each element should trigger the same function, but with a unique ID. for(var i = 0; i < 10; i++) { var p = document.createElement("p"); var t = document. ...

What is the best way to streamline this using Javascript or jQuery?

Looking for a way to simplify the code for 4 vertical sliding panels? Check out the following script: $(".sliding-panels").click(function() { var n = $(this).attr("number"); var panels = $(".panel"); panels.not(".panel" + n).removeClass("pa ...

How do I iterate through my state in React Redux?

Currently, I am delving into Redux by creating a to-do list in React. I have been pondering on the utilization of the map function to iterate over the state so that I can display the data stored within different div elements. Here is my initial state: cons ...

The issue of the marker vanishing upon refreshing the page on AngularJS

Currently, I am encountering a rather peculiar issue. Upon the initial page load, the code snippet below correctly displays a marker at the specified coordinates and ensures the map is properly centered: <div class="paddingtop"> <map data-ng- ...

Discovering the channel editor on Discord using the channelUpdate event

While working on the creation of the event updateChannel, I noticed that in the Discord.JS Docs, there isn't clear information on how to identify who edited a channel. Is it even possible? Below is the current code snippet that I have: Using Discord. ...

Utilizing PHP variables to dynamically assign names to radio input tags, and then extracting their values using jQuery or JavaScript

I am facing an issue with my PHP file that generates radio buttons based on unique pets ids. The variable $idperro is constantly changing to distinguish the set of radio buttons. My goal is to insert the value inside the p tag. Here's the PHP code sn ...

Is there a way to retrieve the dynamically generated text content of an element using document.write?

I am encountering an issue similar to the following: <div id="myDiv"><script>document.write('SOMETHING');</script></div> My goal is to extract the content inside the script tag, which in this case is "SOMETHING" ...

Managing options post initialization in egjs-flicking: A comprehensive guide

In my Vue2 project, I am currently utilizing egjs-flicking. I am looking for a solution to implement different align options based on the screen size (mobile or desktop). Is there a method to accomplish this without having to destroy or reinitialize the ...

The three.js library encountered an ERROR 404 ( File Not Found ) when trying to import an existing file

Error: GET http://localhost:port/js/three net::ERR_ABORTED 404 (Not Found) I am currently working on a web development project using Three JS. I downloaded the master Zip of ThreeJS from the official website of Three JS I copied the JS files from the Bui ...

Choose JSON information and modify it utilizing NODE.js with identical data

Feeling stuck.. I have a JSON file with some data and I need to manipulate it. Take a look at my JSON structure: [{ "method": "GET", "path": "/", "aliases": "", "name": "rootPath", "handler": "generatedApps/avion01/actions.HomeHandler" }, { "method": "GET ...

Is it possible to turn off security features for a Heroku Postgres database?

My project doesn't involve sensitive data, so I'm not concerned about security vulnerabilities. I believe the issue lies in the connection between the App/server and the DB. I've searched on Youtube and Google for solutions, but the informa ...

Ensuring continuous user login during webpage refreshes with the help of React and local storage

Currently, I am working on implementing the use of local storage to ensure that upon refresh, the user remains logged in rather than being signed out each time. Successfully, I have been able to store data in local storage by utilizing the following code ( ...