This was a gnarly process for me to get the hang of. Pinia is so much better and easier to use but since Nova 4 uses vuex, so will I.
There are a few things you need.
- A namespaced module part of a vuex store, not a whole vuex store as Nova covers that.
import Tool from './pages/Tool';
import Vuex from 'vuex';
import myStore from './stores/myStore';
Nova.booting((app, store) => {
// this is the easiest way to add a module to Nova's store
// 'myVendor' will not be namespaced until it comes across myStore.js first namespaced: true
store.registerModule(
'myVendor', myStore,
);
app.use(Vuex);
Nova.inertia('Tool', Tool);
});
- The partial store ('./stores/myStore.js')
const state = {
count: 0,
};
const mutations = {
increment(state) {
state.count++
},
};
export default {
// namespaced to 'myVendor'
namespaced: true,
modules: {
myStore: {
// namespaced to 'myVendor/myStore'
namespaced: true,
state,
// getters,
// actions,
mutations,
},
},
};
- To access your store ('./pages/Tool.vue')
<script setup>
import {defineOptions} from 'vue';
import {useStore} from 'vuex';
import Layout from '../layouts/LayoutOverride.vue';
// if you want to override Nova's default layout but want some of Nova's goodies like MainHeader, then you will need to alias({'@': path.join(__dirname, '../../vendor/laravel/nova/resources/js/')}) in your webpack.mix.js
defineOptions({
layout: Layout,
});
const store = useStore();
// count should be 0
console.log(store.state.myVendor.myStore.count);
// increment()
store.commit('myVendor/myStore/increment');
// count should be 1
console.log(store.state.myVendor.myStore.count);
</script>
Options API does give you more convenient helpers but I prefer Composition API