How to call vuex from a laravel blade file?

Member

by lew , in category: PHP Frameworks , 4 months ago

How to call vuex from a laravel blade file?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 4 months ago

@lew 

To call Vuex from a Laravel Blade file, you can do the following:

  1. Make sure you have included the Vuex store script in your HTML file. You can include it in the head section of your blade file or include it in your app.js file if you are using Laravel Mix.
1
2
3
4
<head>
  <script src="/js/vue.min.js"></script>
  <script src="/js/vuex.min.js"></script>
</head>


  1. Define your Vuex store in a separate JavaScript file (e.g., store.js) and import it in your blade file.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  }
});


  1. Initialize your Vuex store in your main Vue instance in your blade file.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<div id="app">
  <!-- Your app content here -->
</div>

<script>
  import store from './store.js';

  new Vue({
    el: '#app',
    store: store
  });
</script>


  1. Now you can access your Vuex store in your components or methods using this.$store.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<template>
  <div>
    <p>Count: {{ $store.state.count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
export default {
  methods: {
    increment() {
      this.$store.commit('increment');
    }
  }
}
</script>


By following these steps, you can easily call Vuex from a Laravel Blade file and manage your application's state using Vuex.