Why when I use Vue.component to load the two commented components below, I get the following error in the javascript console while it works with import ?
Uncaught ReferenceError: dashboard is not defined
app.js:
Vue.component('left-menu', require('./components/LeftMenu.vue').default);
// Vue.component('dashboard', require('./components/foo/dashboard.vue').default);
// Vue.component('members', require('./components/foo/members.vue').default);
import dashboard from './components/foo/dashboard.vue';
import members from './components/foo/members.vue';
const routes = [
{
path: '/dashboard',
component: dashboard
},
// {
// path: '/members',
// component: members
// }
];
Because you use dashboard variable in your routes, this variable exists in "import way" but not in "Vue component way"
In the example that generates errors the components are not recognized as variables, so you should do something like :
const dashboard = {
template: `<div>Dashboard</div>` ,
}
const routes = [
{
path: '/dashboard',
component: dashboard
},
// {
// path: '/members',
// component: members
// }
];
Related
When I run the project, it displays ReferenceError: getters is not defined as per following image:
app.js file:
store.js file:
What is problem causing this error?
Thanks.
You should use store.getters.variable_name to retrieve state value.
Sample code for retrieving accessToken:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
accessToken: null
},
getters: {
accessToken: state => state.accessToken
},
actions: {
doSomethingsHere({ commit }, somethingData) {
console.log('accessToken: ' + store.getters.accessToken)
}
}
})
export default store
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();
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
I am Using Laravel 5.5 and Vue.js 2.0
When i open example.com and click on Display Items then this url triggered example.com/items
and here are results
and When i open directly this url example.com/items it shows me only json response that i am getting from Laravel without creating any view in html (Vue.js).
See Below:
How Can I Get Exact Results in Browser by Visiting Direct Urls like example.com/items without visiting example.com first.
Updated
Here is My Vue routes.js File
import Example from './components/ExampleComponent.vue'
import CreateItem from './components/CreateItem.vue'
import DisplayItem from './components/DisplayItem.vue'
import EditItem from './components/EditItem.vue'
export const routes = [
{ name: 'Example', path: '/', component: Example },
{ name: 'CreateItem', path: '/items/create', component: CreateItem },
{ name: 'DisplayItem', path: '/items', component: DisplayItem },
{ name: 'EditItem', path: '/items/:id/edit', component: EditItem }
];
Getting Response From Laravel Like This
$items = Items::all();
// dd($items);
return response()->json($items);
DisplayItems.vue File Vue.js Code
<script>
export default {
data(){
return{ items: [] }
},
created: function()
{
this.fetchItems();
},
methods: {
fetchItems()
{
this.axios.get('/items').
then(response => {
this.items = response.data;
});
},
deleteItem(id)
{
let uri = '/items/'+id;
this.items.splice(id, 1);
this.axios.delete(uri);
}
}
}
</script>
Laravel is returning a JsonResponse from the route /items, hence why you see JSON in the browser. Vue binds the JSON to dom elements.
You would need to modify the route to /items so that it returns JSON if $request->wantsJson() and a regular Response if non ajax.
[BEHAVIOUR]
laravel have it's own server with routes.
When you trying to refresh custom Vue.js route, it shows overrides Vue.js routes with laravel route and shows you only JSON response.
[SOLUTION]
You should create Vue.js application and Use laravel-echo or laravel broadcasting and use laravel api.
Now make each request from Vue to direct API and Get Response.
I have been working on an Angular 2 project using lazy loading. It's working well, but what I need is to get the module name from the server and then create a route, but it's not working.
Here is what I have:
import { Routes, RouterModule } from '#angular/router';
function getRoutes(): Routes{
let x: any = [
{path: '', redirectTo: 'welcome', pathMatch: 'full'},
{path: 'backend', loadChildren: 'app/backend/backend.module'}
]
return x;
}
export const routes: Routes = routess();
export const routing = RouterModule.forRoot(routes);
And here is, what do i need:
import { Routes, RouterModule } from '#angular/router';
function getRoutes(): Routes{
let x: any;
$.get( "api/getRoutes", function( data ) {
x = data; //object array from server
});
return x;
}
export const routes: Routes = routess();
export const routing = RouterModule.forRoot(routes);
The problem is, that the function getRoutes is not waiting for the server result and returns empty data.
Is there any way to wait for the server data and then add data to the routes?
Use NgModule just for basic routing setup (/welcome, etc.), then somewhere else in your app load routes and update router configuration. You can then use resetConfig():
this.http.get('/api/getRoutes')
.subscribe(config => this.router.resetConfig(config))