I'm learning Vue router. And I want to made programmatic navigation without using <router-link> in templates file.
My router and view:
router = new VueRouter({
routes: [
{path : '/videos', name: 'allVideos', component: Videos },
{path : '/videos/:id/edit', name: 'editVideo', component: VideoEdit },
]
});
new Vue({
el: "#app",
router,
created: function(){
if(!localStorage.hasOwnProperty('auth_token')) {
window.location.replace('/account/login');
}
router.push({ name: 'allVideos' })
}
})
So by default I push to 'allVideos' route and inside that component I have a button and method for redirecting to ''editVideo'
button:
<button class="btn btn-sm btn-warning" #click="editVideo(video)">Edit</button>
method:
editVideo(video) {router.push({ name: 'editVideo', params: { id: video.id } })},
It works fine. But when I try to get id inside a VideoEdit component using $route.params.id I got error Uncaught ReferenceError: $route is not defined
Maybe it's because I'm not using npm for now just a cdn version of Vue and Vuerouter. Any solutions? Thanks!
Updated: btw in Vue dev tool I see $route instance inside the component
Updated:
var VideoEdit = Vue.component('VideoEdit', {
template: ` <div class="panel-heading">
<h3 class="panel-title">Edit {{vieo.name}}</h3>
</div>`,
data() {
return {
error: '',
video: {},
}
},
created: function () {
console.log($route.params.id);
},
})
Thanks to Sandeep Rajoria
we found solution, need to use this.$route except $route inside a component
For those who getting the error after adding this
TypeError: Cannot read property '$route' of undefined
We need to use a regular function instead of ES6 arrow functions
data: function() {
return {
usertype: this.$route.params.type
};
},
This worked for me.
import Vue from 'vue'
import Router from 'vue-router';
Vue.use(Router)
const router = new VueRouter({
routes: [
{path : '/videos', name: 'allVideos', component: Videos },
{path : '/videos/:id/edit', name: 'editVideo', component: VideoEdit },
]
});
new Vue({
el: "#app",
router,
created: function(){
if(!localStorage.hasOwnProperty('auth_token')) {
window.location.replace('/account/login');
}
this.$router.push({ name: 'allVideos' });
}
})
If you're using vue v2 & vue-router v2 then in vue-cli generated boilerplate way to access router e.g. from component is to import router (exported in router/index.js)
<script>
import Router from '../router';
then in your code you can use router functions like:
Router.push('/contacts'); // go to contacts page
For those attempting to use es6 arrow functions, another alternative to #Kishan Vaghela is:
methods: {
gotoRegister() {
this.$router.push('register')
}
}
as explained in the first answer of Methods in ES6 objects: using arrow functions
In my case these previous solutions don't work for me so
i did the following
<script>
import Router from '../router';
then in your code you can use this one
this.$router.push('/contacts');
Related
Im using Vue Router. In my code I used to have:
<div v-bind:is="page.component_name" v-bind:page="page"></div>
Which worked, and the page data was passed to the component. But how do I do the same with a router-view? This doesn't seem to work:
<router-view v-bind:page="page"></router-view>
js:
var vm = new Vue({
...,
router : new VueRouter({
routes : [
{ path: '/foo', component: { template: '<div>foo</div>', created:function(){alert(1);} } },
//{ path: '/bar', component: { template: '<div>bar</div>', created:function(){alert(2);} } },
{ path: '/bar', component: Vue.component("ti-page-report") }
]
}),
...
});
vue-router has a dedicated page in docs on how to pass props to router-view.
Passing Props to Route Components
Example snippet from docs:
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true },
// for routes with named views, you have to define the `props` option for each named view:
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
})
If you are looking for simplified usage, props can still be passed the same way they are passed to any component. But component that is used for rendering the route (the one that is specified in route definition) should expect to receive the props.
Here is simple usage example of passing props to router-view:
I personally decided to use provide/inject feature: preserving reactivity with minimal overhead.
The component ("ti-page-report") that needs to access the props being sent just needs to add it:
<template>
<div>
<h1>Now you can access page: {{ page }}</h1>
</div>
</template>
export default {
name: "TiPageReport",
props: ['page'], // can now be accessed with this.page
...
};
See https://v2.vuejs.org/v2/guide/components-props.html for how to use props properly.
So ive been looking into vue and been experiencing an issue which i cant seem to find the solution for. Im using Vue and Vue-router. I started with the basic vue + webpack template which gave the initial boilerplate.
I've successfully added additional routes to the predefined routes which is working as expected (games, tournaments, stats and users routes works just fine). However now im unable to get additional routes to work. the "gaming" route doesnt work, ive also tried adding additional routes which does not seem to work either.
So this is my current router file (index.js):
import Vue from 'vue'
import Router from 'vue-router'
const Gaming = () => import('#/components/gaming.vue');
const Home = () => import('#/components/home.vue');
const Game = () => import('#/components/game.vue');
const Tournament = () => import('#/components/tournament.vue');
const Users = () => import('#/components/users.vue');
const Stats = () => import('#/components/stats.vue');
const router = new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/games',
name: 'Game',
component: Game,
},
{
path: '/wtf',
name: 'Gaming',
components: Gaming,
},
{
path: '/tournaments',
name: 'Tournament',
component: Tournament
},
{
path: '/users',
name: 'Users',
component: Users
},
{
path: '/stats',
name: 'Stats',
component: Stats
}
]
});
export default router;
Vue.use(Router);
All my routes works as expected except the "Gaming" route. The "Gaming" component looks like this:
<template>
<div>
<h1>WTF?!?!?!?!?=!?!</h1>
</div>
</template>
<script>
export default {
name: 'Gaming',
components: {},
data() {
return {}
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
</style>
Ive tried to pretty much copy/paste a working component, And only change the name, as well as the template. But it seems to have issues. Initially i had done the route component imports the normal "boilerplate" way
import Stats from '#/components/Stats'
Which pretty much had the same result, Except this would cause an exception when attempting to navigate to the "gaming" route.
Cannot read property '$createElement' of undefined
at render (eval at ./node_modules/vue-loader/lib/template-compiler/index.js?{"id":"data-v-c9036282","hasScoped":false,"transformToRequire":{"video":["src","poster"],"source":"src","img":"src","image":"xlink:href"},"buble":{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./src/components/gaming.vue (app.js:4240), <anonymous>:3:16)
All other routes worked. Ive also tried to re-create all the files and re-do the specific route which doesnt seem to work either. So im at a loss of what i can do to fix this issue?
Here i attempt to inspect the route, And as you can see the component is missing "everything"
Inspecting the route
Also tried looking with the vue addon for chrome, Where the component does not get loaded into the view
Vue Chrome Extension
Uploaded the project to gdrive if someone want to tweak around with it
Google Drive Link
Found the issue:
const router = new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/games',
name: 'Game',
component: Game,
},
{
path: '/wtf',
name: 'Gaming',
components <----------: Gaming,
// Should be component not componentS
},
{
path: '/tournaments',
name: 'Tournament',
component: Tournament
},
...
Also, you should use the standard method of importing. Without that error, I would've never found the issue.
It's my first post on stackoverflow, so sorry in advance if I do something incorrectly. My question;
I've setup a VueJS project, and I'm trying to reach data that I put in the App.vue from another component. To do this, I use this.$root.count for example, but it returns undefined.
Main.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
routes: [{
path: '/',
name: 'home',
component: function (resolve) {
require(['./components/Hello.vue'], resolve)
}
}, {
path: '/race-pilot',
name: 'racePilot',
component: function (resolve) {
require(['./components/RacePilot.vue'], resolve)
}
}
});
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
});
App.vue:
<template>
<div>
<div class="menu" ref="menu">
<router-link :to="{ name: 'home' }">Home</router-link>
<router-link :to="{ name: 'racePilot' }">Race Pilot</router-link>
</div>
<div id="app">
<router-view></router-view>
</div>
</div>
</template>
<style src="./assets/css/app.scss" lang="scss"></style>
<script>
import Hello from './components/Hello'
export default {
name: 'app',
components: {
Hello
},
data () {
return {
count: '0'
}
}
}
</script>
RacePilot.vue:
<template>
<div class="race-pilot">
</div>
</template>
<script>
export default {
name: 'RacePilot',
mounted() {
console.log(this.$root.count);
}
}
</script>
So the last log returns undefined. However, if I log this.$root, I do get the object. Anybody any idea? Thanks in advance!
Vuex is fine and all, but if you just want to expose a property to all of your views in a router based app, you can set it on the router-view.
<router-view :count="count"></router-view>
Then your view component just needs to accept it as a prop.
export default {
props:["count"],
name: 'RacePilot',
mounted() {
console.log(this.count);
}
}
this.$root references the top level Vue instance (new Vue...) and not the App VueComponent.
it is really hacky, other solutions are preferable, but this could work:
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App },
methods: {
getCount() {
return this.$children[0].count
}
},
});
and using getCount() in RacePilot.vue:
export default {
name: 'RacePilot',
mounted() {
console.log(this.$root.getCount());
}
}
You are trying to access data which is stored in App.vue but this data will be local to the component and not accessible globally.
App.vue is not the root instance (referred to by $root), instead it is the first component within the root instance which is actually created at main.js. It is during this creation time, you need to pass the data which will then be exposed for all child components via $root.
Here is the relevant portion of main.js, modified accordingly :-
new Vue({
el: '#app',
data: { count: 0 },
router,
template: '<App/>',
components: { App }
});
Tip : To confirm that App.vue is indeed the first child of root instance, try comparing the references of this.$root with this.$parent. It should returntrue which means that root instance is the parent of App.vue.
References :-
https://v2.vuejs.org/v2/guide/instance.html
https://v2.vuejs.org/v2/api/#vm-root
https://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-the-Root-Instance
It should had worked as it is, as it is working here.
However a better way to manage global variables, which are available across components should be solved by state machine. Vue has Vuex for that purpose as stated here.
You should not do it like that.
Definitely you should not try to access other components like that.
To share data between components you can either use props (one-way binding) or Vuex to make data accessible and editable from all components through store.
You can use global $store or $router if you will start your Vue app this way:
new Vue({
el: '#q-app',
router,
store
render: h => h(require('./App'))
})
Then you can access store (for state change or access state (do not mutate state this way)) - this.$store.state.yourStaneName
You can also make the App component the actual root by passing the component directly to the Vue instance, which would look something like this:
new Vue(App).$mount('#app')
You'll probably have to move the router to App.vue, but this will make sure that this.$root will resolve to your App component directly.
I'm currently making use of the WordPress REST API, and vue-router to transition between pages on a small single page site. However, when I make an AJAX call to the server using the REST API, the data loads, but only after the page has already rendered.
The vue-router documentation provides insight in regards to how to load data before and after navigating to each route, but I'd like to know how to load all route and page data on the initial page load, circumventing the need to load data each time a route is activated.
Note, I'm loading my data into the acf property, and then accessing it within a .vue file component using this.$parent.acfs.
main.js Router Code:
const router = new VueRouter({
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/tickets', component: Tickets },
{ path: '/sponsors', component: Sponsors },
],
hashbang: false
});
exports.router = router;
const app = new Vue({
router,
data: {
acfs: ''
},
created() {
$.ajax({
url: 'http://localhost/placeholder/wp-json/acf/v2/page/2',
type: 'GET',
success: function(response) {
console.log(response);
this.acfs = response.acf;
// this.backgroundImage = response.acf.background_image.url
}.bind(this)
})
}
}).$mount('#app')
Home.vue Component Code:
export default {
name: 'about',
data () {
return {
acf: this.$parent.acfs,
}
},
}
Any ideas?
My approach is to delay construction of the store and main Vue until my AJAX call has returned.
store.js
import Vue from 'vue';
import Vuex from 'vuex';
import actions from './actions';
import getters from './getters';
import mutations from './mutations';
Vue.use(Vuex);
function builder(data) {
return new Vuex.Store({
state: {
exams: data,
},
actions,
getters,
mutations,
});
}
export default builder;
main.js
import Vue from 'vue';
import VueResource from 'vue-resource';
import App from './App';
import router from './router';
import store from './store';
Vue.config.productionTip = false;
Vue.use(VueResource);
Vue.http.options.root = 'https://miguelmartinez.com/api/';
Vue.http.get('data')
.then(response => response.json())
.then((data) => {
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store: store(data),
template: '<App/>',
components: { App },
});
});
I have used this approach with other frameworks such as Angular and ExtJS.
You can use navigation guards.
On a specific component, it would look like this:
export default {
beforeRouteEnter (to, from, next) {
// my ajax call
}
};
You can also add a navigation guard to all components:
router.beforeEach((to, from, next) => {
// my ajax call
});
One thing to remember is that navigation guards are async, so you need to call the next() callback when the data loading is finished. A real example from my app (where the guard function resides in a separate file):
export default function(to, from, next) {
Promise.all([
IngredientTypes.init(),
Units.init(),
MashTypes.init()
]).then(() => {
next();
});
};
In your case, you'd need to call next() in the success callback, of course.
I've comprised my own version based on all the great responses to this post.. and several years having passed by as well giving me more tools.
In main.js, I use async/await to call a prefetch service to load any data that must be there on startup. I find this increases readability. After I get the data comms, I then dispatch it to the appropriate vuex store module in the beforeCreate() hook.
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import { prefetchAppData } from '#/services/prefetch.service';
(async () => {
let comms = await prefetchAppData();
new Vue({
router,
store,
beforeCreate() {
store.dispatch('communityModule/initialize', comms);
},
mounted() {},
render: h => h(App)
}).$mount('#app');
})();
I feel compelled to warn those be careful what you prefetch. Try to do this sparingly as it does delay initial app loading which is not ideal for a good user experience.
Here's my sample prefetch.service.js which does the data load. This of course could be more sophisticated.
import api from '#api/community.api';
export async function prefetchAppData() {
return await api.getCommunities();
}
A simple vue store. This store maintains a list of 'communities' that the app requires to be loaded before application start.
community.store.js (note im using vuex modules)
export const communityModule = {
namespaced: true,
state: {
communities: []
},
getters: {
communities(state) {
return state.communities;
},
},
mutations: {
SET_COMMUNITIES(state, communities) {
state.communities = communities;
}
},
actions: {
// instead of loading data here, it is passed in
initialize({ commit }, comms) {
commit('SET_COMMUNITIES', comms);
}
}
};
Alright, I finally figured this thing out. All I'm doing is calling a synchronous ajax request within my main.js file where my root vue instance is instantiated, and assigning a data property the requested data as so:
main.js
let acfData;
$.ajax({
async: false,
url: 'http://localhost/placeholder/wp-json/acf/v2/page/2',
type: 'GET',
success: function(response) {
console.log(response.acf);
acfData = response.acf;
}.bind(this)
})
const router = new VueRouter({
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/tickets', component: Tickets },
{ path: '/sponsors', component: Sponsors },
],
hashbang: false
});
exports.router = router;
const app = new Vue({
router,
data: {
acfs: acfData
},
created() {
}
}).$mount('#app')
From here, I can use the pulled data within each individual .vue file / component like so:
export default {
name: 'app',
data () {
return {
acf: this.$parent.acfs,
}
},
Finally, I render the data within the same .vue template with the following:
<template>
<transition
name="home"
v-on:enter="enter"
v-on:leave="leave"
v-bind:css="false"
mode="out-in"
>
<div class="full-height-container background-image home" v-bind:style="{backgroundImage: 'url(' + this.acf.home_background_image.url + ')'}">
<div class="content-container">
<h1 class="white bold home-title">{{ acf.home_title }}</h1>
<h2 class="white home-subtitle">{{ acf.home_subtitle }}</h2>
<div class="button-block">
<button class="white home-button-1">{{ acf.link_title_1 }}</button>
<button class="white home-button-2">{{ acf.link_title_2 }}</button>
</div>
</div>
</div>
</transition>
</template>
The most important piece of information to take away, is that all of the ACF data is only being called ONCE at the very beginning, compared to every time a route is visited using something like beforeRouteEnter (to, from, next). As a result, I'm able to get silky smooth page transitions as desired.
Hope this helps whoever comes across the same problem.
Check this section in docs of Vue Router
https://router.vuejs.org/guide/advanced/data-fetching.html
So first of you have to write method that would fetch data from your endpoint, and then use watcher to watch route.
export default {
watch: {
'$route': 'fetchItems'
},
methods: {
fetchItems() {
// fetch logic
}
}
}
Since you are working with WP Rest API, feel free to check my repo on Github https://github.com/bedakb/vuewp/blob/master/public/app/themes/vuewp/app/views/PostView.vue#L39
I am trying to make a VueJS app but I am failing even with the simplest examples.
I am using Laravel 5.3 with pre-built support for VueJS (version 1, I tried version 2 as well).
Here is my Example.vue component
<template>
<div class="profile">
{{ name }}
</div>
</template>
<script>
export default {
data () {
return {
name: 'John Doe'
}
}
}
</script>
And here is the main code
Vue.component('example', require('./components/Example.vue'));
const app = new Vue({
el: '#app'
});
This is the error that shows up everytime in console:
[Vue warn]: Property or method "name" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in component )
Any ideas whats wrong?
Thanks
In your script tags instead of export default use:
module.exports = {
data() {
return { counter: 1 }
}
}
This should work for you
Call the component inside your template
Vue.component('example', {
template: `<div class="profile">{{ name }}</div>`,
data () {
return {
name: 'John Doe'
}
}
})
const app = new Vue({
el: '#app'
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app"><example></example></div>
The problem is that you are trying to load the component 'example' from that file but you didn't give a name to it. You should use:
<script>
export default {
name: 'example',
data() {
return {
name: 'John Doe'
}
}
}
</script>
Or load the component the following way (not sure if extension .vue is needed):
require('./exmaple').default();
If you are using Babel you can also load the components without giving them a name using this syntax:
import Example from ./example
Also checkout this post to get some more info in case you use Babel