I need router only for checkout page, checkout component is loaded asynchronously.
components.js
const VueComponents = [
......
{ name: 'cart-page', constructor: () => import(/*webpackChunkName: 'checkoutAndAccount'*/ './cartPage/cartPage') },
......
];
app.js
.....
import { VueComponents } from './components/components';
.....
if (VueComponents) {
const componentsToRegister = VueComponents.filter(vueComponent => !!document.querySelectorAll(`${vueComponent.name}, [is="${vueComponent.name}"]`).length);
for (const vueComponent of componentsToRegister) {
Vue.component(vueComponent.name, vueComponent.constructor);
}
}
this.vueInstance = new Vue({
el: this.rootElement
});
.....
I Don't want to do this :
this.vueInstance = new Vue({
el: this.rootElement,
router
});
I need to add router to the vue instance only on "cart-page" component, so something like :
cartPage.vue
name: 'cart-page',
beforeCreate() {
vueInstance.extends(router);
}
How do I access vue instance?
How do I add router to it?
Thanks.
Related
I wanted to add the dynamic routes and use the same component for all the dynamic routes. I have tried the following code to render the components, but I have got the error that says:
[vue-router] "path" is required in a route configuration.
What is the proper way of adding the dynamic routes and display the same components?
const Foo = {
template: '<div>Foo</div>'
}
const Home = {
template: '<div>Home</div>'
}
const router = new VueRouter({
mode: 'history',
routes: [{
path: '/',
component: Home
}]
})
const app = new Vue({
router,
el: "#vue-app",
methods: {
viewComponent: function(path, method) {
debugger;
let tf = `${path}/${method}`;
let newRoute = {
path: tf,
name: `${path}_${method}`,
components: {
Foo
},
}
this.$router.addRoute([newRoute])
},
}
});
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.14"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>
<div id="vue-app">
<a v-on:click="viewComponent('api/contact','get')">ddd</a>
<router-view></router-view>
</div>
Main problem is you are passing array into addRoute
Second problem is missing / at the beginning of the path (without it, you will get a "Non-nested routes must include a leading slash character" error)
Finally use $router.push to go to the new route
const Foo = {
template: '<div>Foo</div>'
}
const Home = {
template: '<div>Home</div>'
}
const router = new VueRouter({
mode: 'history',
routes: [{
path: '/',
component: Home
}]
})
const app = new Vue({
router,
el: "#vue-app",
methods: {
viewComponent: function(path, method) {
let tf = `/${path}/${method}`;
let newRoute = {
path: tf,
name: `${path}_${method}`,
component: Foo,
}
this.$router.addRoute(newRoute)
this.$router.push({ name: newRoute.name })
},
}
});
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.14"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>
<div id="vue-app">
<a v-on:click="viewComponent('api/contact','get')">ddd</a>
<router-view></router-view>
</div>
require('./bootstrap');
window.Vue = require('vue');
Vue.component('exampleComponent1', require('./components/exampleComponent1.vue'));
Vue.component('exampleComponent2', require('./components/exampleComponent2.vue'));
const app = new Vue({
el: '#app'
});
from the above code, I want to pass data from exampleComponent1 to exampleComponent2 when some event has occurred in exampleComponent1.
What is the optimal solution for this ??
The key here is to set their parent component as the one receiving from the first (using emit) and sending to the second (using props):
const component1 = Vue.component('component1', {
template: '#component1',
data() { return { name: '' } },
methods: {
updateName() { this.$emit("namechanged", this.name); }
}
});
const component2 = Vue.component('component2', {
template: '#component2',
props: ['name'],
});
new Vue({
el: "#app",
components: { component1, component2 },
data() { return { name: '' } },
methods: {
updateName(newName) { this.name = newName; }
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div><component1 #namechanged="updateName"/></div>
<div><component2 :name="name"/></div>
</div>
<template id="component1"><input v-model="name" #input="updateName"/></template>
<template id="component2"><p>Input From component 1: {{name}}</p></template>
You can use a Event Bus for this.
// in some global file
const EventBus = new Vue();
// creating or emitting event
EventBus.$emit('someEvent', 'some-data')
// listen to the event
EventBus.$on('someEvent', function(data) {
console.log(data) // 'some-data
})
I'm practicing laravel with vuejs and I'm wondering if possible to use vuejs (component) variable in other file with pure javascript.
I created my.js and registered it in app.js.
require('./my.js');
const app = new Vue({
el: '#app'
});
In my.js I have following code.
alert(app.name)
name is variable used in vuejs component. As a result I received alert undefined. Please give me some guidelines.
You must run the code in the correct order:
function MyFunc(vm) {
alert(vm.name)
}
const app = new Vue({
data: {
name: 'FooBar'
}
});
MyFunc(app)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
Example 1
my.js:
export default function(vm) {
alert(vm.name);
}
main.js:
import Vue from "vue";
import MyFunc from './my';
const app = new Vue({
data: {
name: 'FooBar'
}
});
MyFunc(app)
Example 2
my.js:
export default (app) => alert(app.name);
vue.js:
import Vue from 'vue';
export default new Vue({
data: {
name: 'FooBar'
}
});
main.js:
import bar from './vue'
import foo from './my'
foo(bar)
I have a simple demo I wanna try out to learn more about VueJS components. But when I load my page, I receive the error: Unexpected Token Import, in this line
import GISView from './components/GISView.vue';
when I remove this, GISView is not defined. I use Laravel 5.4 and webpack for compiling the scripts. Why is the component not found?
Main.js
import GISView from './components/GISView.vue';
window.Vue = Vue;
window.Event = new class {
constructor() {
this.Vue = new Vue();
}
fire(event, data = null) {
this.Vue.$emit(event, data);
}
listen(event, callback) {
this.Vue.$on(event, callback);
}
};
window.app = new Vue({
el: '#app',
components: {
GISView: GISView
},
data: {
},
methods: {
init: function() {
this.$broadcast('MapsApiLoaded');
}
}
});
GISView.vue
<script>
import GoogleMaps from '../mixins/GoogleMaps.js';
export default {
mixins: [GoogleMaps]
}
</script>
I really got stuck for hours on this because just by the code, it should work I would say.
You are not using a proper parser like vueify to properly parse .vue files in your webpack/gulp script.
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');