unexpected token error importing a vuex store to laravel page - vuejs2

New-ish to Vue nd extremely new to Vuex. Im trying to import a store to my main page from which all my components branch out, but I keep getting an "unexpected token {" error in the browser console. I read through the documentation, but I cant find anything that would address this issue. I have tried changing every bit of syntax I can, and it doesnt seem to make a difference. The brackets around store in the import appear to be the problem, but when I remove them, i just get a new "unexpected identifier", or an "unexpected string" error. Am I importing it incorrectly? This format works fine on all my components, just not on this new vue instance.
vuex-test.blade.php
#extends('core.core_layouts.core_blank')
#section('browsertitle')
#endsection
#section('top-css')
#endsection
#section('breadcrumb')
#endsection
#section('main')
<component :is="currentView" v-bind="currentProperties"></component>
#endsection
#section('bottom-js')
<script>
import { store } from './../stores/store1.js';
var app = new Vue({
el:"#app",
store,
data: {
currentView: 'org-list',
choseOrg: {{ $org }},
}, // end data
computed: {
currentProperties: function() {
if (this.currentView === 'org-list') { return { } }
if (this.currentView === 'add-org') { return { parentOrg: '' } }
}
},
mounted : function() {
}, // end mounted
methods: {
}, // end methods
components: {
},
});
</script>
#endsection
store1.js
export const store = new Vuex.Store({
state: {
safelyStoredNumber: 'ret',
count: 2,
},
mutations: {
setOrgIdentity(state, orgID) {
state.OrgID = orgID
}
}
});

Per comments:
Yes, I get the error at the browser.
import won't work there. It is meant to run on node.js, during the build phase of a vue-cli-based project.
If you are deploying the code directly to browser, you will need to use code that is supported by the browser. In this case, the solution to import other JavaScript files is standard <script> tags.
So, in your code, change:
import { store } from './../stores/store1.js';
to something like (change the path to what is more appropriate):
<script src="./../stores/store1.js"></script>
And in store1.js (because export is too meant for node.js), replace:
export const store = new Vuex.Store({
With:
window.store = new Vuex.Store({

Related

Data passed as props is not updating in Vue 2

I can't understand why data passed as props is not updating when data changes. I tried different ways, but for some reason, the frontend knows nothing about data manipulation. Here is my code base:
For Loop
<SingleElement v-for="addon of addons" :key="addon.id"
:id="addon.id"
:title="addon.name"
:description="addon.description"
:active="addon.active" // This is the part I need to update
></SingleElement>
The SingleElement Template
<template>
<div class="column is-4">
<b-field>
<b-switch v-model="isActive"></b-switch>
</b-field>
</div>
</template>
<script>
import { store, methods } from '../../../store';
export default {
name: "single-element",
props: {
id: Number,
title: String,
description: String,
active: Boolean,
docURL: String,
category: String
},
data() {
return {
"isActive" : this.active
}
},
}
</script>
The Store
import axios from "axios";
export const store = Vue.observable({
"addons": [],
"activatedAddons": [],
"settings": {}
});
export const methods = {
activateAllAddons() {
store.activatedAddons = [];
for (let addon of store.addons) {
store.activatedAddons.push(addon.id);
addon.active = true;
}
},
deactivateAllAddons() {
store.activatedAddons = [];
for (let addon of store.addons) {
addon.active = false;
}
},
}
The process in short: On click, I call the store method activateAllAddons or deactivateAllAddons. These methods are changing the store.activatedAddons and store.addons data. For example I change the active boolean. But my switch do not react to this changes. Why?
*What I tried
I tried to change the data in different ways.
Way 1
-> Changing the addon boolean in the store
:active="addon.active"
Way 2
-> Creating an additional method to check the status:
:active="isActive(addon)"
and:
isActive(addon) {
return store.activatedAddons.includes(addon.id);
}
But no way. The frontend seems to know nothing about the changes. When I log the variables in the console, the changes definitely are there. What's the problem here?

Vuex registerModule method registers an empty module

I have two modules. One load statically, the other dynamically.
StaticLoadingStore.js:
export default {
namespaced: false,
state() {
return {
propertySL: 'Some value from a statically loaded module',
}
},
getters: {
getPropertySL(state) {
return state.propertySL
},
},
}
DynamicLoadingStore.js
export default {
namespaced: true,
state() {
return {
propertyDL: 'Some value from a dynamically loaded module',
}
},
getters: {
getPropertyDL(state) {
return state.propertyDL
},
},
}
Dynamically loaded module shows that it is empty. Why?
HelloWorld.vue:
<template>
<div>
<h1>SL</h1>
<h5>propertySL:</h5>
<p>{{ propertySL }}</p>
<h5>stateSL:</h5>
<code>{{stateSL}} </code>
<h1>DL</h1>
<h5>propertyDL:</h5>
<p>{{ propertyDL===undefined?'undefined':propertyDL }}</p>
<!-- return undefined -->
<h5>stateDL:</h5>
<code>{{stateDL}} </code>
<!-- return {} -->
</div>
</template>
<script>
import SLModule from '../StaticLoadingStore'
const DLModule = () => import('../DynamicLoadingStore.js');
export default {
data: () => ({
stateSL: '',
stateDL: '',
}),
computed: {
propertySL() {
return this.$store.getters['getPropertySL']
},
propertyDL() {
return this.$store.getters['dlModule/getPropertyDL']
},
},
created() {
this.$store.registerModule('slModule', SLModule);
this.stateSL = JSON.stringify(this.$store.state['slModule'], null, 2);
this.$store.registerModule('dlModule', DLModule());
this.stateDL = JSON.stringify(this.$store.state['dlModule'], null, 2);
}
}
</script>
My knowledge in vue and js is very limited, and I ask the question through Google translator, so I apologize in advance for incompetence.
Without waiting for an answer, he began to experiment.
That's how it worked.
DynamicLoadingStore.js
...
async created() {
const moduleLoader = await DLModule();
this.$store.registerModule('dlModule', moduleLoader.default);
...
But why this is not as recommended in the examples is not clear.
New problem. Reactivity does not work. alert(this.$store.getters['dlModule/getPropertyDL'])
gives expected data.
But the propertySL in template is empty. Tell me what's wrong, please.
But why this is not as recommended in the examples is not clear.
If you talking about this official guide Dynamic Module Registration. I think the author doesn't want to specify how to get the module since there are a lot of ways to do.
In your example I think both modules should call dynamic module, static module is the module that declared at store creation.
But you import it with different methods which are static import and dynamic import. You can read more about import from MDN.
To use dynamic import, there is no need to wrap import statement with function:
...
await import('../DynamicLoadingStore.js')
...
...
// This will useful when you use dynamic component
() => import('../DynamicLoadingStore.js')
...
New problem. Reactivity does not work.
alert(this.$store.getters['dlModule/getPropertyDL']) gives expected
data.
But the propertySL in template is empty. Tell me what's wrong, please.
If you register slModule before dlModule, the propertySL should still work fine but not propertyDL.
The reason is this is the how computed property works, since you are using async created instead of created, the computed property doesn't wait until async created finished. So when Vue try to compute the dependency of the property it cannot do correctly because your getters will return undefined.
You can solve this problem by use another data to trigger computed property to recompute like this:
this.dlModuleReady && this.$store.getters["dlModule/getPropertyDL"];
See example.

Vue: how to apply multiple global mixins

I am currently working on a Vue project including multiple applications.
It has project-wide used methods and application-wide used methods.
Therefore, I created 2 mixins which need to be available in every Vue component. However, I don't know how to implement it using Vue.mixin().
Please help.
I tried this. Not work..
The error says "Cannot read property 'VALIDATION' of undefined".
Somehow URL is not imported. URL() returns a object where urls are defined according to either DEV or PRODUCTION mode.
import global_mixin from './global_mixin.js'
import application_mixin from './application_mixin.js'
Vue.mixin(global_mixin)
Vue.mixin(application_mixin)
new Vue({
el: '#app',
render: h => h(App)
})
global_mixin.js
export default {
data() {
return {
// data items
}
}
}
application_mixin.js
import { URL } from './_util'
export default {
data() {
return {
URL_VALIDATION: URL().VALIDATION
}
}
}
_util.js
import store from './_store'
export const URL = () => {
const urls = {
PROD: {
VALIDATION: '/api/web/company/profile/validation',
PROFILE: '/api/web/company/profile',
COUNTRY: '/api/app/countries',
ADDRESS: '/api/web/address'
},
DEV: {
PROFILE: '/data/profile_company.json',
VALIDATION: 'https://httpbin.org/post',
COUNTRY: '/data/countries.json',
ADDRESS: '/data/zip.json'
}
}
return urls[store.getters.mode]
}

Can be exclude `this` keyword in vue.js application?

Actually I am following Douglas Crockford jslint .
It give warning when i use this.
[jslint] Unexpected 'this'. (unexpected_a) 
I can not see any solution around for the error . Don't say add this in jslist.options and mark it true.
Is there is any approach without using this?
EDIT
ADDED CODE
// some vue component here
<script>
export default {
name: "RefereshPage",
data() {
return {
progressValue: 0
}
},
methods:{
getRefreshQueue(loader){
console.log(this.progressValue); // ERROR come here [jslint] Unexpected 'this'. (unexpected_a) 
}
}
}
</script>
Check out this jsfiddle. How can you avoid using this?
https://jsfiddle.net/himmsharma99/ctj4sm7f/5/
as i already stated in the comments:
using this is an integral part of how vue.js works within a component. you can read more about how it proxies and keeps track of dependencies here: https://v2.vuejs.org/v2/api/#Options-Data
As others have said, you're better off just disabling your linter or switching to ESLint. But if you insist on a workaround, you could use a mixin and the $mount method on a vue instance to avoid using this altogether ..
let vm;
const weaselMixin = {
methods: {
getdata() {
console.log(vm.users.foo.name);
}
},
mounted: function () {
vm.getdata();
}
};
vm = new Vue({
mixins: [weaselMixin],
data: {
users: {
foo: {
name: "aa"
}
}
}
});
vm.$mount('#app');
See the modified JSFiddle
As you can see, this only complicates what should be a fairly simple component. It only goes to show that you shouldn't break the way vue works just to satisfy your linter.
I would suggest you go through this article. Particularly important is this part ..
Vue.js proxies our data and methods to be available in the this context. So by writing this.firstName, we can access the firstName property within the data object. Note that this is required.
In the code you posted, you appear to be missing a } after getRefreshQueue definition. It's not the error your linter is describing, but maybe it got confused by the syntax error?
It is possible using the new Composition API. Vue 3 will have in-built support, but you can use this package for Vue 2 support.
An example of a component without this (from vuejs.org):
<template>
<button #click="increment">
Count is: {{ state.count }}, double is: {{ state.double }}
</button>
</template>
<script>
import { reactive, computed } from 'vue'
export default {
setup() {
const state = reactive({
count: 0,
double: computed(() => state.count * 2)
})
function increment() {
state.count++
}
return {
state,
increment
}
}
}
</script>

Vue-apollo doesn't populate data object

I am experimenting using vue-apollo with nuxt by implementing the #nuxtjs/apollo module. I have a working GraphQL server running on localhost:4000. I wrote the following code :
<template>
<div>
<p v-for = "item in stuff" :key="item.id">item.name</p>
</div>
</template>
<script>
import stuff from '~/apollo/queries/stuff'
export default {
apollo: {
stuff: {
query: stuff,
variables: {
limit: 10
}
}
},
data () {
return {
stuff: []
}
}
}
</script>
stuff.gql :
{
stuff {
id
name
}
}
client-config :
import { ApolloLink } from 'apollo-link'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
export default (ctx) => {
const httpLink = new HttpLink({ uri: 'http://localhost:4000' })
// middleware
const middlewareLink = new ApolloLink((operation, forward) => {
const token = process.server ? ctx.req.session : window.__NUXT__.state.session
operation.setContext({
headers: { authorization: `Bearer ${token}` }
})
return forward(operation)
})
const link = middlewareLink.concat(httpLink)
return {
link,
cache: new InMemoryCache()
}
}
The observant reader will see that I basically copied the example code from the docs. What I expected to happen was that the data object of my vue component would get updated with the first 10 results of stuff from my backend. However, I see everything in an $apolloData object which is not accessible from the component. Also, the data is not limited to the first 10 entries. Could someone point out what I am doing wrong? Because I don't see it.
I also tried :
apollo: {
products: {
query: stuff,
variables () {
return {
limit: 10
}
}
}
}
And with all variations on the prefetch option.
OK, so I installed a fresh version of the nuxt starter template today and migrated only the essentials to get apollo working. It worked immediately. I have no clue what was causing the error and due to the fact that I already had a dozen packages installed we probably will never know.