Custom Event isn't be tracked by using applicationInsight within vue - javascript

I am using azure application-insight to track events of a self-built search engine written within VUE.
I wrapped the application-insight SDK as a service and export a function.
import {
ApplicationInsights
} from '#microsoft/applicationinsights-web'
const appInsights = new ApplicationInsights({
config: {
instrumentationKey: "xxxx",
autoTrackPageVisitTime: true,
enableAutoRouteTracking: true,
enableRequestHeaderTracking: true,
enableResponseHeaderTracking: true
}
})
appInsights.loadAppInsights();
appInsights.trackEvent();
export function useAppInsights() {
return appInsights
}
Then in my search-view page (search.vue), I call the service of application-insight and register two custom events to track.
`
<script>
import {
useAppInsights
} from '../services/AppInsights'
useAppInsights().trackEvent("search page loaded!");
useAppInsights().trackPageView({
name: 'search page'
});
export default {
methods: {
addQuery(key) {
useAppInsights().trackEvent({
name: 'SelectTag',
properties: {
searchInput: key
}
});
this.searchInput = key;
this.handleSearch();
},
}
};
</script>
The search.vue is integrated into the main.js using the router.
import Search from './components/Search.vue'
import Product from './components/Product.vue'
const routers = [{
path: '/search',
name: 'Search',
component: Search
},
{
path: '/product',
name: 'Product',
component: Product
},
]
export default routers
import Vue from "vue";
import VueRouter from "vue-router";
import "element-ui/lib/theme-chalk/base.css";
import routers from "./router";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import App from "./App.vue";
import axios from "axios";
Vue.config.productionTip = false;
Vue.use(VueRouter);
Vue.use(ElementUI);
Vue.use(axios);
const router = new VueRouter({
mode: "history",
routes: routers,
});
new Vue({
el: "#app",
router,
render: (h) => h(App),
});
The catalogue of my project is
But in my azure application-insight portal, I cannot see any events at all.
Does anyone have solutions to this condition? Many thanks!

I referred the following articles to realize trackevent codes:
https://dev.to/ardc_overflow/monitorando-uma-aplicacao-vuejs-com-o-application-insights-9h1
https://github.com/microsoft/applicationinsights-js#npm-setup-ignore-if-using-snippet-setup
In the second article, the sample of event tracking using application-insight is very clear:
appInsights.trackEvent({
name: 'some event',
properties: { // accepts any type
prop1: 'string',
prop2: 123.45,
prop3: {
nested: 'objects are okay too'
}
}
});
emmm...so I am trapped by the condition.

Related

Nothing renders in vue.js project

After creating a new Vue project with Vue CLI 3 and deleting all default views and components, I created two new views. None of them appears when changing url and instead I see blank page and no errors in console. In Chrome DevTools inspector I see that <div id="app"></div> is empty. Vue.js Devtools plugin doesn't trigger Vue on the page at all. I think I might miss something in my settings but can't find what can cause such behaviour.
This my main.js:
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
Vue.config.productionTip = false;
new Vue({
router,
store,
render: (h) => h(App),
}).$mount('#app');
This is my App.vue:
<template>
<div id="app">
<router-view />
</div>
</template>
This is index.js of router
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';
import Auth from '../views/Auth.vue';
Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/auth',
name: 'auth',
component: Auth,
},
];
const router = new VueRouter({
mode: 'history',
scrollBehavior() {
return { x: 0, y: 0 };
},
base: process.env.BASE_URL,
routes,
});
export default router;
This is vue.config.js
module.exports = {
configureWebpack: {
devtool: 'source-map',
},
chainWebpack: config => {
config.module
.rule('js')
.use('babel-loader')
.loader('vue-loader')
.tap(options => {
return options;
});
},
css: {
loaderOptions: {
sass: {
data: `
#import "#/assets/styles/variables.scss";
#import "#/assets/styles/global.scss";
`,
},
},
},
};
Home.vue:
<template>
<h1>Home page</h1>
</template>
<script>
export default {
name: 'home',
};
</script>
If you are using vue-cli you shouldn't have vue.config.js populated - as a fresh start -, hence there is a good chance your config is faulty.

Access data variable inside a component

I made a repository of Vue using
vue init webpack my-app
Now, my main.js is something like this --
// The Vue build version to load with the import command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
Vue.component('todo-item', {
template: '<li>{{ todo }}</li>',
props: ['todo']
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App :groceryList="groceryList"/>',
data:{
message: 'abcdefghi',
groceryList: [
{ id: 0, text: 'Vegetables' },
{ id: 1, text: 'Cheese' },
{ id: 2, text: 'Whatever else humans are supposed to eat' }
]
}
})
My App.vue file has the template with id app as mentioned in the main.js
<template>
<div id="app">
At Parent: {{ groceryList[1].text }}
<br/>
<div>{{ message }}</div>
<router-view/>
<Table/>
<Users/>
</div>
</template>
<script>
import Users from './components/Users'
import Table from './components/Table'
export default {
name: 'App',
components: {
Users,
Table,
},
}
</script>
Here,I keep getting errors that cannot read property groceryList and message of undefined. I have read the documentation of vue and according to it I am not making any mistakes. So, what is the problem here?
In main.js, you should declare data as a function and pass :message to App component
new Vue({
el: '#app',
router,
components: { App },
template: '<App :groceryList="groceryList" :message="message"/>',
data () {
return {
message: 'abcdefghi',
groceryList: [
{ id: 0, text: 'Vegetables' },
{ id: 1, text: 'Cheese' },
{ id: 2, text: 'Whatever else humans are supposed to eat' }
]
}
}
})
and in App.vue, you need to declare groceryList and message as props
<script>
import Users from './components/Users'
import Table from './components/Table'
export default {
name: 'App',
props: ['message', 'groceryList']
components: {
Users,
Table,
},
}
</script>

Property or method "X" is not defined on the instance with vuex and vue router

This problem is annoying me, i'm new with Vue and i'm trying to make a simple app to get practice.
Right now I'm using Vuex and Vue Router, here is the code:
The routes file, very simple, just a lazy load for the routes that aren't home.
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/tracks',
name: 'tracks',
component: () => import(/* webpackChunkName: "about" */ './views/Tracks.vue')
}
]
})
The view component, it just render the view childs:
<template>
<div id="tracks">
<logo></logo>
<search></search>
<songs></songs>
</div>
</template>
<script>
import Logo from '#/components/Logo.vue'
import Search from '#/components/Search.vue'
import Songs from '#/components/Songs.vue'
export default {
name: 'tracks',
components: { Logo, Search, Songs }
}
</script>
The songs component, this is the container where i make the logic (just list things right now)
<template>
<section id="track-list" class="columns is-centered">
<div class="column is-4" v-show="!songList.length">
<div class="notification is-danger">
No tracks loaded :(
</div>
</div>
</section>
</template>
<script>
import { mapState } from 'vuex'
import SongCard from './SongCard.vue'
export default {
name: 'songs',
components: { SongCard },
computed: {
...mapState([ 'songs' ])
}
}
</script>
I think the problem is in the rendering cycle, where the component is mounted the data isn't loaded yet, but this isn't async data (not mine, at least) but hardcoded in the state, initalized as empty array:
const state = {
songList: [ ],
song: null
}
// actions
const actions = {
}
// mutations
const mutations = {
// [tracks.GET_TOP](state, payload) {},
// [tracks.GET_TRACK](state, payload) {}
}
export default {
namespaced: true,
state,
actions,
mutations
}
Since i use Vuex, i don't use the data() {} key, else i use computed... what can i do here? I'm lost.
Edit, here is the complete store file:
import Vue from 'vue'
import Vuex from 'vuex'
import artists from './modules/artists'
import songs from './modules/songs'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
artists,
songs,
countries: {
state: {
selected: 'Mexico',
list: [
{ value: 'spain', name: 'España' },
{ value: 'mexico', name: 'México' },
{ value: 'argentina', name: 'Argentina' }
]
}
}
},
actions,
mutations
})
The main issue here is that songs is not a state, it's a namespaced module so it cannot be access directly like ...mapState(['songs']).
To map state of the songs module of the store, we use mapState helper syntax intended for use with namespaced module:
computed: {
...mapState('some/nested/module', {
a: state => state.a,
b: state => state.b
})
}
So, the correct syntax with respect to this question would be:
...mapState('songs', [ 'song', 'songList' ])
Note that you can also pass an object instead of array just like in the example above.
For more, refer this.

Vue2: How to redirect to another page using routes

How can I redirect to another vue page from my script code. I am using router.push() but cannot redirect to my desired vue page.
Following is my source code.
src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import HomePage from '#/components/HomePage'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'IndexPage',
component: IndexPage
},
{
path: '/homepage',
name: 'HomePage',
component: HomePage
}
]
})
src/components/IndexPage.vue
<script>
import VueRouter from 'vue-router'
export default {
name: 'IndexPage',
methods: {
redirectUser() { // this method is called on button click
if (1 == 1)
{
router.push('/homepage');
//this.$router.push('/homepage');
}
}
}
}
</script>
After running this code I am getting error which states:
ReferenceError: router is not defined at eval
src/main.js
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
window.Vue = Vue
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
Furthermore, I can access that same link from browser http://localhost:8080/#/homepage. But cannot redirect to it from my script code.
import Vue and VueRouter
and then call
Vue.use(VueRouter)
then in your method,
this.$router.push({name: 'HomePage'})
EDIT
You need to import both Vue and Vue Router if you want to use it in your code, that's why you are getting router is not defined at eval.
And also use
this.$router.push('/homepage');
Try this in your src/components/IndexPage.vue
<script>
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
export default {
name: 'IndexPage',
methods: {
redirectUser() { // this method is called on button click
if (1 == 1)
{
this.$router.push('/homepage');
}
}
}
}
</script>
Use your component instance property to access the router:
this.$router.push({name: 'HomePage'})
And do you have it in your app?
new Vue({
router,
render: h => h(App)
}).$mount('#app')
Thanx for the feedback friends. I was not importing my router file on my vue. The updated line of code is:
src/components/IndexPage.vue
<script>
import router from '../router/index.js' // Just added this line and code works !!
export default {
name: 'IndexPage',
methods: {
redirectUser() { // this method is called on button click
if (1 == 1)
{
router.push({name: 'HomePage'})
}
}
}
}
</script>
You can try the following code:
function redirect(page) {
window.location.href = page;
}

How to get a key from route module using vuex-router-sync

I've got a little Vuex store (like below) and I use vuex-router-sync to keep it in sync. This adds a router module to my store, but how would I get this object out of the store as there don't seem to be any associated getters with this module?
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import module1 from './modules/module1'
import module2 from './modules/module2'
import module3 from './modules/module3'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
module1,
module2,
module3
}
})
main.js
import App from './views/App/App'
import store from './store'
import router from './router'
import { sync } from 'vuex-router-sync'
// sync router with store
sync(store, router)
new Vue({
el: '#app',
store,
router,
render: h => h(App)
})
My state would look something like this:
{
module1: {
cheese: true
},
module2: {
crackers: true
},
module3: {
wine: true
},
route: {
from: {}
fullPath:"/path/to/cheese"
hash:""
meta: {}
name:"cheese"
params: {}
path:"/path/to/cheese"
query: {}
}
}
Basically what I'm trying to do is add a title in my app header that updates depending on what page/view you are on.
Header.vue
export default {
name: 'header',
computed: {
getRouteTitle () => {
return this.$store.getters.getRouteTitle
}
}
}
Header.html
<header>
<h1>{{ getRouteTitle }}</h1>
</header>
Found a solution that works quite well. vuex-router-sync fires an action to telling us that the route has changed. Within one of our existing modules you can listen out of this and make a subsequent mutation. For me this would be setting the title from the router/ROUTE_CHANGED action payload.
router.js
const router = [
{
name: 'Cheese',
path: 'cheese',
component: Cheese,
meta: { title: 'Calendar', requiresAuth: true }
},
]
module1.js
import * as types from '../mutation-types'
// Initial State
const state = {
cheese: true,
title: 'App'
}
// Getters
export const getters = {
getRouteTitle: state => state.title
}
// Mutations
export const mutations = {
'router/ROUTE_CHANGED' (state, payload) {
state.title = payload.to.meta.title
}
}
export default {
getters,
mutations,
state
}
Hope that makes sense and please let me know if there is a better solution :)
******* UPDATE *********
A super easy way is just to get the $router instance in your component like this:
<h1>{{$route.name}}</h1>
Which would render to:
<h1>Cheese</h1>

Categories