Vuex state no showing in Laravel - laravel

I have a Laravel installation and want to use vuejs for the fornt-end. So, I ran npm install --save vuex and all the installation was successful.
The in app.js ( /resources/js/app.js ) I imported the store file and added it to the vue instance object:
import store from './store/store'
const app = new Vue({
el: '#app',
router,
store
});
Inside store.js I have the following:
import Vue from 'vue'
import Vuex from 'vuex'
import jobs from './modules/jobs'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
jobs
}
});
The jobs.js (store/modules/jpbs.js):
const state = {
value: 1,
jobs: [
{ name: 'Milton', age: '23'}
]
}
const getters = {
jobs: state => {
return state.jobs;
},
value: state => {
return state.value;
}
}
//EDITED
export default {
state,
getters
};
Ultimately, I tried to test how things go if I get anything from the state or getter:
<button type="button" class="btn bgDark mt-2" data-toggle="modal" data-target="#exampleModalCenter">
Add New {{ this.$store.state.value }}
</button>
When I visit my site, the value does not show and I dont see errors in the console.
Is there perhaps anything I missed in the vuex configuration?

If you are trying to get the value from your jobs.js module you need the to reference it like this:
this.$store.state.jobs.value
( the this is optional)
If you look at the first example in the Vuex Documents - The last two lines of code are
store.state.a
store.state.b
where a and b are the module names (jobs in your case)

this should not be used within html templates, Vue automatically assumes that variables or objects written within brackets {{ }} are attributes of this.

Related

Can a custom vue package export pieces of a Vuex State, that could then be imported/used within a Laravel Project's Vuex State

Hey Stackoverflow community!
I've got a question regarding Vuex in a Laravel/Vue Project, that is also importing a custom Vue components library/package.
I'd like to have our package export certain pieces of Vuex state (state, mutations, getters, etc) that relate specifically to our package.
I'd like these pieces to work with our Laravel Project's Vuex Instance. The hope is that this would allow the project to use state pieces from the custom package, as well as state pieces specific to the Laravel project, in one Vuex Instance.
Is this possible or even a good approach? The package is meant to be re-usable and is not project-specific, but it would be ideal if the Laravel Project could read/manipulate/interact the package state from its own Vuex State.
Here are some relevant code snippets:
Custom Component Library - main.js
import ExampleComponent from './components/ExampleComponent.vue'
import AnotherComponent from './components/AnotherComponent.vue'
export {
ExampleComponent,
AnotherComponent
}
Laravel Project - app.js
import {ExampleComponent, AnotherComponent} from 'vue-components-library'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
filterData: {
page: 1
},
fetchResultsFlag: 0
},
mutations: {
updateFilterData: (state, filterData) => {
Object.entries(filterData).forEach(([key, value]) => {
state.filterData[key] = value
});
state.fetchResultsFlag = 1
},
incrementPage: (state) => {
state.filterData.page++
state.fetchResultsFlag = 1
},
resetFetchResultsFlag: (state) => {
state.fetchResultsFlag = 0
}
},
getters: {
filterData: state => {
return state.filterData
},
fetchResultsFlag: state => {
return state.fetchResultsFlag
},
page: state => {
return state.filterData.page
}
}
})
const app = new Vue({
el: '#app',
store: store
});
Any help or insight is greatly appreciated!
Thanks.

NativeScript vue, vuex and urlhandler

Edit
I'm using https://github.com/hypery2k/nativescript-urlhandler to open a deep link within my app - using NativeScript vue, and vuex. It seems that in order to get at the methods needed to do routing [$navigateTo etc] this plugin needs to be set up slightly differently from the examples given in docs.
import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);
import { handleOpenURL } from 'nativescript-urlhandler';
new Vue({
mounted() {
handleOpenURL( (appURL) => {
console.log(appURL)
// Settings is the variable that equals the component - in this case settings.
this.$navigateTo(Settings);
});
},
render: h => h("frame", [h(Home)]),
store: ccStore
}).$start();
handleOpenURL needs to be called within Mounted - then you can parse out the appURL and reference the page (component) that you wish to navigate to. I have been advised against calling handleOpenURL from within router - but I'm not sure why, and it works without error - and I have access to the methods for routing... so if anyone knows if this is a bad idea - please let me know :) Thanks!
All the stuff below that I wrote before has probably confused things - I'm referencing components within my vuex store to make them easily available from the router.
This is based on a solution by https://github.com/Spacarar - it can be found here: https://github.com/geodav-tech/vue-nativescript-router-example. It's a great solution because you don't have to include every single component within each component to use in navigation - it gives an almost vue router like experience.
I'm using https://github.com/hypery2k/nativescript-urlhandler to open a deep link within my app - however, I'm having problems opening the link.
In my app.js file, I have the following:
import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);
....
import { handleOpenURL } from 'nativescript-urlhandler';
import ccStore from './store/store';
handleOpenURL(function(appURL) {
// I have hardwired 'Settings' in for testing purposes - but this would be the appURL
ccStore.dispatch('openAppURL', 'Settings');
});
....
new Vue({
render: h => h("frame", [h(Home)]),
store: ccStore
}).$start();
I'm storing the route state within vuex, and have various methods which work (clicking on a link loads the component). However, handleOpenURL exists outside of vue... so I've had to access vuex directly from within the handleOpenURL method. I've created an action specifically for this case - openAppURL.. it does exactly the same thing as my other methods (although I've consolidated it).
When clicking on an app link, I am NOT taken to the page within the app. I have put a console log within openAppURL and can see it is being called, and the correct route object is returned... it just doesn't open the page. The SetTimeOut is used because nextTick isn't available from within vuex.
I am at a loss on how to get the page to appear...
const ccStore = new Vuex.Store({
state: {
user: {
authToken: null,
refreshToken: null,
},
routes: [
{
name: "Home",
component: Home
},
{
name: "Log In",
component: Login
},
...
],
currentRoute: {
//INITIALIZE THIS WITH YOUR HOME PAGE
name: "Home",
component: Home //COMPONENT
},
history: [],
},
mutations: {
navigateTo(state, newRoute, options) {
state.history.push({
route: newRoute,
options
});
},
},
actions: {
openAppURL({state, commit}, routeName ) {
const URL = state.routes[state.routes.map( (route) => {
return route.name;
}).indexOf(routeName)];
return setTimeout(() => {
commit('navigateTo', URL, { animated: false, clearHistory: true });
}, 10000);
},
....
}
etc....
I have been advised to post my findings as the answer and mark it as correct. In order to use nativescript-urlhandler with vue, you must initialise the handler from within vue's mounted life cycle hook. Please see above for greater detail.
import Vue from "nativescript-vue";
import Vuex from "vuex";
Vue.use(Vuex);
import Settings from "~/components/Settings";
import { handleOpenURL } from 'nativescript-urlhandler';
new Vue({
mounted() {
handleOpenURL( (appURL) => {
console.log(appURL) // here you can get your appURL path etc and map it to a component... eg path === 'Settings. In this example I've just hardwired it in.
this.$navigateTo(Settings);
});
},
render: h => h("frame", [h(Home)]),
store: ccStore
}).$start();

laravel + vue router cannot get parameters from url

I try to get parameters from url
let's say url contains:
localhost:8000/blog?q=hello
I want to grab hello to trigger function call
What I had declare in app.js in laravel webpack:
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
routes: []
})
const app = new Vue({
router
});
export default app;
In blog page, I try to extract the parameter from url
new Vue ({
el: "#blog-content",
},
mounted: function() {
q = this.$route.query.q
console.log(q)
}
)
I npm run dev to compile and run the blog page it show error:
TypeError: Cannot read property 'query' of undefined
what is wrong? I am sure that Vue Router is properly installed in the application.
I think that the blog page that you use is not correct.
You recreate another Vue instance and in that case that new instance doesn't have a router passed to it. So I think that's why this.$router is undefined.
Also you don't pass the view Component to your router so it doesn't know what to look for with the specific url.
Here's your app.js file corrected
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import Blog from './views/Blog';
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/blog',
name: 'blog',
component: Blog
},
]
});
The blog view page template : views/Blog.vue
<template>
<div class="wrapper">
My blog page
</div>
</template>
<script>
export default {
data() {
return {
myvariable : ''
}
},
mounted() {
let q = this.$route.query.q;
console.log(q);
},
};
</script>
Now it should works correctly :)
Edit : Also you don't need to export the app variable in your app.js
Remove the following line export default app; at the end of the file

Laravel & Vuejs mixins : how to attribute a new value to shared variable?

I can use the mixin variables test and the method changeTest, when when I attribute a new value to the variable test, it's only applied in one component. How to have it changed globally, on all components using it ?
My mixins are set in the file resources/js/mixins.js:
export default {
data() {
return {
test: 'foo',
};
},
methods: {
changeTest(v) {
this.test = v;
}
}
}
Then, I have my two components comp1.vue and comp2.vue in resources/js/components/, both looking like this:
<template>
<div>
{{ test }}
</div>
</template>
<script>
import myMixins from '../mixins'
export default {
mixins: [ myMixins ],
}
</script>
Both components are in my home.blade.php like this:
#extends('layouts.app')
#section('content')
<comp1></comp1>
<comp2></comp2>
#ensection
for making a common variable (state) between all instances in vue.js you can use vuex. it's so simple, just add vuex to your packages and make an instance like this:
import Vuex from 'vuex'
const store = new Vuex.Store({
state: {
test: 'foo',
},
mutations: {
setTest(state, payload) {
state.test = payload
}
},
});
now you need to add this store to your main vue instance:
import Vue from 'vue'
Vue.use(Vuex);
let vm = new Vue({
el: '#app',
store,
// ...
});
all done. now in every component you can access the states by this.$store.state. for making life easier, you can define a computed variable like this:
computed: {
test() {
return this.$store.state.test
}
}
to change the state you just need to commit the setTest mutation. you have to add this mutation to methods and simply call it like this:
methods: {
...Vuex.mapMutations(['setTest']),
myMethod() {
// do this
this.setTest('some value');
// do that
}
}
you can also make a global mixin like i told you before to add this computed and mutation to every instance like this: (add this before make the main vue instance)
Vue.mixin({
computed: {
test() {
return this.$store.state.test
}
},
methods: {
...Vuex.mapMutations(['setTest']),
}
});
but i don't recommend to do this because when the project grow big, it gets so hard to avoid name confusion. it's better to make them separately for each component to chose proper names.
you can use mixin method on main Vue instance like this:
import Vue from 'vue'
import MyMixin from './mixins.js'
Vue.mixin(MyMixin);
It will apply this mixin for all instance no matter how deep they are.

Vue js: Uncaught SyntaxError: Unexpected identifier at import line

I am trying to use vue plugins but everytime I do I always get an Unexpected Identifier on the import line. Any suggestions?
HTML
<div id="content">
<h1>#{{ message }}</h1>
<v-select :value.sync="selected" :options="options"></v-select>
</div>
JS
new Vue({
el: '#content',
data: {
message: 'Hello Worldy'
},
import vSelect from "vue-select"
export default {
components: {vSelect},
data() {
return {
selected: null,
options: ['foo','bar','baz']
}
}
}
});
You can't import from where you're trying to
import vSelect from "vue-select"
new Vue({
el: '#content',
components: {
vSelect: vSelect
}
});
and then do the rest of it inside your component definition
Just in case another person encounter this same error sign in the console when using vue. As for me in my case, the import script was automatically created for one of the components I called in my Laravel blade template (by PhpStorm).
The importation is recommended to be called in the Js file where the instance of Vue is made, because of the need to compile import syntax of ES6 to ES5. See: https://medium.com/#thejasonfile/a-simple-intro-to-javascript-imports-and-exports-389dd53c3fac
Hope this helps someone save some time.
When you insert tag, which is related to your Vue.js component, in your blade file, PhpStorm indeed like Oluwatobi Samuel Omisakin wrote inserts such code
<script>
import MyComponent from "../../../js/components/myComponent";
export default {
components: {MyComponent}
}
</script>
in the end of your blade file. And this is brings you error in console. Just delete it and make import in you app.js file.

Resources