Software
how to destroy all the data of the current page
in my page , I have a real-time chart which updates every 3 seconds I used setInterval(function(){...} , 3000) for make the chart updates. but my problem is when I move to another page(by javascript) every thing are destroyed except my interval , so when I back to the chart page , it load every thing again and setInterval method works twice on every 3 seconds which makes duplicated points on mu chart.
this is destroy method every line works except the myInterval one
destroy() { this.num=0; this.c=0; this.startLive = false; clearInterval(this.myInterval); }my problem appears just when I go to another page then back.
How can i access other component's data in vuejs at last component?
You can find the project in here. https://github.com/sahinsalih/vuejs-app
How to correctly use "scoped" styles in VueJS single file components?
Docs on VueJS states that "scoped" should limit styles to the component. But if I create 2 components with same "baz" style, it will leak from one component into another:
foo.vue
<template> <div class="baz"> <Bar></Bar> </div> </template> <style scoped> .baz { color: red; } </style>bar.vue
<template> <div class="baz">bar</div> </template> <style scoped> .baz { background-color: blue; } </style>I expect that "baz" will be different in both components. But after generating a web page I can see yje red text on blue background, that means that "foo"'s scoped style affects "bar" component. The generated code looks like this:
<div class="baz" data-v-ca22f368> <div class="baz" data-v-a0c7f1ce data-v-ca22f368> bar </div> </div>As you can see, the "leak" is intentionally generated by VueJS via specifying two data attributes into "bar" component. But why?
Show plain HTML before Vue.js loads
I have an avatar widget built with Vue.js on a sidebar in my app. It takes a split-second to load and this causes the sidebar to jank. Is there a way that I can show plain HTML in place of the Vue app while it is loading? Basically the opposite of v-cloak.
How toss Vue's transpiling to es5
The Vue cli typically transpiles es6 to es5 with babel and webpack.
Is there a Vue cli built template or template option that just transforms the .vue files correctly but does not run babel to convert the code to es5? And does not bundle?
My goal is to simply transpile the .vue files and I'll do the rest to integrate the results into my es6 + modules workflow.
Note: I tried using the "simple" cli template but couldn't find documentation on how to use it.
Vuejs 2 missing request headers on one route only
I have two components called Employees and UserProfile. The first one lists an array of users, the second one shows the user's details.
Problem is when I call the server in order to get the user details no custom headers are applied to the http call. I have no issues with the call to get multilple resources.
The headers I want to add are the headers related to the CORS requirements and one header for Authorization.
I paste here the two methods.
Method fetchData in Employees component (working):
fetchData: function () { this.$http.get( process.env.BASE_API_URL + '/api/user', { headers: { 'Authorization': 'Bearer ' + store.getters.getToken } } ).then(response => { this.employees = response.body }).catch(error => { console.log(error) }) }Headers generated:
Method fetchData in UserProfile component (NOT working):
fetchData: function () { this.user.id = this.$route.params.user_id this.$http.get( process.env.BASE_API_URL + '/api/user/' + this.user.id, { headers: { 'Authorization': 'Bearer ' + store.getters.getToken } } ).then(response => { this.user = response.body }).catch(error => { console.log(error) }) }Headers Generated:
Also the two components are called in the router as follows:
{ path: '/employees', name: 'Employees', component: Employees }, { path: '/employees/:user_id', name: 'UserProfile', component: UserProfile }Any suggestions?
Set up vue js without npm
How can I set up vue js without npm? I'm not able to install npm right now because of some reasons. Is vue.js enough? What am I missing?
P.S.: I've just started to learn vue.js and I don't want to miss something and struggle after I realize I need something that I can get only with npm.
Vue js 2 table sorting
I am trying to create a sortable table by using Vue js 2. I have already generated a table, and now just wondering how to sort this table. Thank you for your help in advance.
Please see below my code
<thead> <tr> <th class="table-header">Metric</th> <th class="table-header" v-for="metric in metricList"><a href="#">{{metric}}</a></th> </tr> </thead> <tbody> <template v-for="item in metricItem"> <tr> <td class="table-cell" style="font-weight:bold"> {{ item }}</td> <template v-for="metric in metricList"> <td class="table-cell"> {{getData[item][metric]}} </td> </template> </tr> </template> </tbody> <script> import { mapGetters, mapMutations } from 'vuex'; export default { name: 'scores', data(){ return { metricList : ["Current", "Min", "Avg", "Max"], metricItem : [ 'Happiness Score', 'Sadness Score' ] } }, computed: { ...mapGetters ([ 'getData', //getter to get data ]) } }and the data set is something like this
getData { Happiness Score { Min : 62, Max : 154, Avg : 103 Current : 100 }, Sadness Score { Min : 66, Max : 54, Avg : 73 Current : 45 },}
Hi guys, I am trying to create a sortable table by using Vue js 2. I have already generated a table, and now just wondering how to sort this table. Thank you for your help in advance.
modal is just draggable top and bottom not to the sides
I am working with vue-js-modal and i already builded my modal and it is working well except i can't move the modal to the sides, just top and bottom if i try to move it to the left or right it doesn't move.
Basicly i followed the inscructions on the github repo.
At the begin i installed the vue-js modal and in my main.js i set it up like this:
import VModal from 'vue-js-modal' Vue.use(VModal, { dialog: true })then on my component i call it like this:
<modal name="modalSection" @closed="checkClose" :draggable="true"> <component :is="getView"> </component> </modal>my hide and show is working well, so i don't need to show it here, the draggable = true just allows me to drag it top and down, i thaught it has something to do because i set bootstrap up and maybe it is inside the grid in a specific col, but i checked it and it doesn't.
Any help?
Thanks
Bootstrap nav-pills dynamic data changes in vue js 2
The jsfiddle was, https://jsfiddle.net/r6o9h6zm/2/
I have used bootstrap nav pills in vue js 2, to display the data based on the selected tab (i.e, if click over the standard non ac room, the record of that particular room need to be displayed) but here i am getting all the three rooms at instance and i have used the following to achieve it, but it gives no result.
Html:
<div id="app"> <div class="room-tab"> <ul class="nav nav-pills nav-justified tab-line"> <li v-for="(item, index) in items" v-bind:class="{'active' : index === 0}"> <a :href="item.id" data-toggle="pill"> {{ item.title }} </a> </li> </ul> <div class="room-wrapper tab-content"> <div v-for="(item, index) in items" v-bind:class="{'active' : index === 0}" :id="item.id"> <div class="row"> <div class="col-md-8"> <div class="col-md-4"> <h3>{{item.title}}</h3> <p>{{item.content}}</p> </div> </div> </div><br> </div> </div>Script:
new Vue({ el: '#app', data: { items: [ { id: "0", title: "Standard Non AC Room", content: "Non AC Room", }, { id: "1", title: "Standard AC Room", content: "AC Room", }, { id: "2", title: "Deluxe Room", content: "Super Speciality Room", }, ], } })How can i get the result with records of only selected room type and others needs to be hidden?
Delete confirmation with Sweet alert in Vue js
I have a comment delete button in vue components.
<button class="button" style="background-color: grey;" @click="destroy">Delete</button>When the button clicked will call the method "destroy"
destroy(){ swal({ title: "Delete this comment?", text: "Are you sure? You won't be able to revert this!", type: "warning", showCancelButton: true, confirmButtonColor: "#3085d6", confirmButtonText: "Yes, Delete it!", closeOnConfirm: true }, function(){ axios.delete('/comment/' + this.comment.id + '/delete'); $(this.$el).fadeOut(300, () => { return toastr.success('Comment deleted.'); }); }); },i expect when alert come out, if users clicked confirm button then process to delete, but seem like when user clicked the delete function are not executed. What is the problems here?
How to load a resource on the client side only in Nuxt.js
I'm trying to build an app using Tone.js on top of Nuxt.js. Tone.js requires the browser's Web Audio API and as Nuxt renders stuff on the server side my build keeps failing.
Nuxt addresses this in the plugin documentation and I've followed that approach in my nuxt.config.js file writing:
module.exports = { plugins: [{src: '~node_modules/tone/build/Tone.js', ssr: false }], }however that results in this error: [nuxt] Error while initializing app TypeError: Cannot read property 'isUndef' of undefined. Looking at Tone's source I'm pretty sure this is because I'm getting it because the code is still being executed on the server side.
I've seen solutions putting the js file into the static folder and checking process.browser but both result in Tone being undefined.
My question seems to be the same as this one if it's helpful additional context
Table cell validation in vuejs and laravel 5.4
I’m very new to VUE and trying loop through dynamically created tables from unique arrays. I have the table creation complete and dynamic table id’s based off a value from the array. I’m trying to validate that either cell[0] in each row contains a specific string or if the last cell[?] which has a select dropdown has been selected and is said string.
I’ve done something similar before in JS like this.
$("#" + t_node + " :selected").each(function (i,sel) { .....///code }
and like this
$("table#"+t_node+" > tbody > tr").each(function(row, tr) { .....///code }
I don’t know how to replicate with VUE. I have a onclick event that once all tables are created the onclick will loop through and validate each table.
Can someone get this example vue.js app to work with techan.js?
I'm pretty sure it has something to do with babel, webpack and d3. I'm trying to get techanjs (http://techanjs.org) to work with vue.js (http://vuejs.org)
Here is an example app. https://github.com/chovy/techan-vue
You can checkout the repo and load up the app with:
git clone https://github.com/chovy/techan-vue cd techan-vue npm install npm run devAs you can see the chart loads but you get errors in the console when you move your mouse around. From my understanding this might be due to d3 live event binding and using babel with webpack but so far I have not found a solution to the problem.
Here is the error:
Uncaught TypeError: Cannot read property 'sourceEvent' of null at __webpack_exports__.a (eval at <anonymous> (renderer.js:2455), <anonymous>:6:26) at __webpack_exports__.a (eval at <anonymous> (renderer.js:9334), <anonymous>:7:99) at SVGRectElement.eval (eval at <anonymous> (renderer.js:8060), <anonymous>:2357:38) at SVGRectElement.eval (eval at <anonymous> (renderer.js:2037), <anonymous>:29:16) __webpack_exports__.a @ sourceEvent.js?354a:5 __webpack_exports__.a @ mouse.js?ab49:5 (anonymous) @ techan.js?5956:2357 (anonymous) @ on.js?519a:27 drag.js?c3c9:10 Uncaught TypeError: Cannot read property 'button' of null at SVGPathElement.defaultFilter (eval at <anonymous> (renderer.js:8340), <anonymous>:16:70) at SVGPathElement.mousedowned (eval at <anonymous> (renderer.js:8340), <anonymous>:47:32) at SVGPathElement.eval (eval at <anonymous> (renderer.js:2037), <anonymous>:29:16)Alternative for setting the srcObject
Setting the "src" attribute of the html video element does not work with Vue.js and Vuex:
<video id="myVideoEl" :src="myStreamSrc" autoplay="autoplay">myStreamSrc is a computed value and is set in a mutation by an event handler:
AddStream: function (state, plMyStream) { state.myRTCPeerConnection.addStream(plMyStream) state.myStreamSrc = plMyStream }When I run my application with that code, I get the following error:
HTTP “Content-Type” of “text/html” is not supported. Load of media resource http://localhost:8080/[object%20MediaStream] failed.
When I do the following:
state.myVideoEl = document.querySelector('#myVideoEl') state.myVideoEl.srcObject = payloadWithMyStreamI do not get any error and the stream is shown. The problem is, I can not use the working code snipped because the referenced elements are added later to the DOM. This code snippet does not work when I bind the html video element in a div with a v-if Vuex.js attribute. Then I just get "undefined" as a result (because the div element with the video element did not exist on page load).
Is there a difference between setting the srcObject and setting the src attribute? I thought that when I set srcObject the video element will have a src attribute, but it does not.
Is it possible to set the srcObject in the video html attribute?
For more info, please visit my theard in the Vue.js forum: https://forum.vuejs.org/t/reference-elements-when-they-rendered-with-v-if/16474/13
Render HTML in Vue.js Grid
I'm currently looking at the following example: https://vuejs.org/v2/examples/grid-component.html
and my goal is to have the data be HTML that is rendered. Here's what I've tried:
// bootstrap the demo var demo = new Vue({ el: '#demo', data: { searchQuery: '', gridColumns: ['html'], gridData: [ { html: '{{{<html><div><p>test</p></div></html>}}}', name: 'Chuck Norris', power: Infinity }, { name: '<html><div><p>test</p></div></html>', power: 9000 }, { name: '<div v-html="<p>Test</p>"></div>', power: 7000 }, ] } });This is a proof of concept before I clean up the other data points. The requirements call for having a single-column grid that has boxes as it's items, with each box being a snapshot of rendered HTML.
We don't want to have to render the HTML to images if possible. In production, the HTML will be the content html of email mailings. Everything else, code wise, is the same as the example posted in the above link.
Thanks
How to mix two arrays of one object in js?
I am going to build a computer game to study economic terms in Russian for Chinese students.
The script of my game is:
- I have 5 random Chinese and five random Russain cards with economic terms. Upper there are Chinese ones, below are Russian ones. Cards are made like jpg files in Photoshop.
- The user must find the particular term in Chinese, then the same one in Russian.
- To make this game more complicated, I should mix terms. Now Chinese terms is just over its Russian translation. I want terms and translation to be mix in random. But Chinese terms should be always over Russian.
Here is my code:
HTML:
<div id="game"> <div class="container"> <div class = "chinese"> <game-card-chinese v-for="card in getSplicedArray(5)" v-bind:gameprop="card"> </game-card-chinese> </div> <div class = "russian"> <game-card-russian v-for="card in getSplicedArray(5)" v-bind:gameprop="card"> </game-card-russian> </div> </div>JS:
Vue.component('game-card-chinese', { props: ['gameprop'], template: '<span><img :src = "gameprop.src_chinese" data-toggle="tooltip" v-bind:title="gameprop.name"/></span>' }) Vue.component('game-card-russian', { props: ['gameprop'], template: '<span><img :src = "gameprop.src_russian" data-toggle="tooltip" v-bind:title="gameprop.description"/></span>' }) var game = new Vue({ el: '#game', data: { splicedCardList:[], cardList: [ { id: 0, src_chinese: 'img/actions/actions_chinese.jpg', src_russian: 'img/actions/actions_russian.jpg', name: "Акция", description: "Акция – ценная бумага, свидетельствующая о внесении средств в капитал акционерного общества и дающая право на получение части прибыли в виде дивидендов" }, { id: 1, src_chinese: 'img/actives/actives_chinese.jpg', src_russian: 'img/actives/actives_russian.jpg', name: "Актив", description: "Актив: часть бухгалтерского баланса (левая сторона), отражающая состав и стоимость имущества организации на определённую дату. Совокупность имущества, принадлежащего юридическому лицу или предпринимателю" }, { id: 2, src_chinese: 'img/arenda/arenda_chinese.jpg', src_russian: 'img/arenda/arenda_russian.jpg', name: "Аренда", description: "Аренда — форма имущественного договора, при которой собственность передаётся во временное владение и пользование (или только во временное пользование) арендатору за арендную плату" }, { id: 3, src_chinese: 'img/amortization/amortization_chinese.jpg', src_russian: 'img/amortization/amortization_russian.jpg', name: "Амортизация", description: "Амортизация — процесс переноса по частям стоимости основных средств и нематериальных активов по мере их физического или морального износа на стоимость производимой продукции (работ, услуг)" }, { id: 4, src_chinese: 'img/assignation/assignation_chinese.jpg', src_russian: 'img/assignation/assignation_russian.jpg', name: "Ассигновать", description: "Ассигновать - Назначить отпуск денег." }, { id: 5, src_chinese: 'img/bankruption/bankruption_chinese.jpg', src_russian: 'img/bankruption/bankruption_russian.jpg', name: "Банкротство", description: "Банкротство — признанная уполномоченным государственным органом неспособность должника (гражданина, организации, или государства) удовлетворить в полном объёме требования кредиторов по денежным обязательствам и (или) исполнить обязанность по уплате обязательных государственных платежей" }, ] }, methods: { getSplicedArray: function(itemLength){ if(this.splicedCardList.length != 0){ return this.splicedCardList; } var itemIndex; for (var i = 0; i<itemLength; i++){ itemIndex = Math.floor(Math.random() * this.cardList.length); this.splicedCardList.push(this.cardList[itemIndex]); this.cardList.splice(itemIndex,1); } return this.splicedCardList; }, mixArray: function(){ var arr1 = [this.cardList.src_chinese]; var arr2 = [this.cardList.src_russian]; var arr3 = new Array(); for(var i in arr1){ var shared = false; for (var j in arr2) if (arr2[j].name == arr1[i].name) { shared = true; break; } if(!shared) arr3.push(arr1[i]) } arr3 = arr3.concat(arr2); },Where is my mistake? What should I do?
Cannot find function from imported module
first of all thanks in advance for the feedback. As I am new to es6 and vuejs I'm starting to have problems using imported Services module throughout the application. The end goal would be to move everything that uses Axios to one BaseService too.
[Vue warn]: Error in mounted hook: "TypeError: __WEBPACK_IMPORTED_MODULE_0__services_AuthService__.a.getCurrentUser is not a function"AuthService.js
import BaseService from './BaseService' export default class AuthService { setCurretUser( user ) { localStorage.setItem("currentUser", user); } getCurrentUser() { return localStorage.getItem("currenUser"); } }App.vue
import Axios from 'axios' import Navbar from './partials/Navbar' import Sidebar from './partials/Sidebar' import AuthService from '../services/AuthService' export default { name: 'app', components: { Navbar, Sidebar }, mounted() { console.log('Component mounted.') }, created() { Axios.get('api/user') .then(function (response) { AuthService.setCurrentUser(response.data); console.log(response); }) .catch(function (error) { console.log(error); }); } }"export 'store' was not found in '../store'
HI all I am trying to import my store into my Vuex Route-Gard.
router/auth-guard.js
import {store} from '../store' export default (to, from, next) => { if (store.getters.user) { next() } else { next('/login') } }store/index.js
import {store} from '../store' export default (to, from, next) => { if (store.getters.user) { next() } else { next('/login') } }The error I am getting export 'store' was not found in '../store'
my vue set up
"dependencies": { "firebase": "^4.3.0", "vue": "^2.3.3", "vue-router": "^2.6.0", "vuex": "^2.3.1"Vue pagination not working only in Chrome
I have a pagination component built with Vue 1, for which I am receiving data from Laravel pagination:
<template> <div class="row"> <div class="col-md-8"> <div v-if="zeroVideos">No videos found for "{{ query }}""</div> </div> <div class="col-md-8"> <single-video v-for="video in videos" :video="video"></single-video> </div> </div> <div class="row justify-content-center"> <pages v-if="meta && videos.length && showPagination" for="videos" :pagination="meta.pagination"></pages> </div> </template> <script> import eventHub from '../events.js' export default { props: ['query'], data () { return { videos: [], meta: null, showPagination: false, zeroVideos: false, } }, methods: { getVideos (page) { this.$http.get('/search/videos?q=' + this.query + '&page=' + page).then((response) => { this.videos = response.data.data this.meta = response.data.meta this.showPagination = response.data.meta.pagination.total_pages > 1 console.log('Videos ' + response.data.meta.pagination.total) this.zeroVideos = response.data.meta.pagination.total < 1 eventHub.$emit('videos.counter', response.data.meta.pagination.total) }) } }, ready() { this.getVideos(1) eventHub.$on('videos.switched-page', this.getVideos) } } </script>For some reason, after I have updated my chrome, pagination stopped working and I am getting undefined for response.data.meta , but on checking the network tab in the console, I am sending the data from the backend:
data[{id: 43, uid: "15883245ef3de1",…}, {id: 44, uid: "15883245ef3de2",…},…] meta:{pagination: {total: 8, count: 8, per_page: 20, current_page: 1, total_pages: 1, links: []}}The pagination works fine on IE, Firefox and Safari, but on Chrome I have problems after updating. What is wrong?