Software
How to fetch data from server in vue js?
I am trying to fetch data from the server using Vue + Vuex + Vue resource.On button click I want to hit Http request and show in list format .I tried like that.Here is my code
https://plnkr.co/edit/EAaEekLtoiGPvxkmAtrt?p=preview
// Code goes here var store = new Vuex.Store({ state: { Item: [] }, mutations: { getItems: function (state) { } }, actions: { fetchData:function (context) { this.$http.get('/data.json', function(v1users) { // this.$set('v1_user',v1users); }); } } }) var httprequest = Vue.extend({ "template": '#http_template', data: function () { return { items: store.state.Item } }, methods: { fetchData: function () { store.dispatch('fetchData') }, } }) Vue.component('httprequest', httprequest); var app = new Vue({ el: '#App', data: {}, });
Load CSS Dynamically according to module loaded with Webpack - VueJS
I have a VueJS application that uses Webpack 2. I am working on VueJS and I will work with a webdesigner that will add CSS classes to the app. The designer wants to have 1 CSS file for the login page (login.css), 1 CSS file for after login (app.css), and etc. So the things is that it is not necessary to load app.css at the login page and vice versa. Besides that the CSS files may have the same classes but will be used for different things. Example: for body tag, he will use font-size 10px in login.css, and on app.css the same body tag he will use font-size 12px. Now I import in my main.js file the CSS files:
import '../src/assets/css/login.css'; import '../src/assets/css/app.css';This way whatever is on app.css overrides login.css.
So how can I load just the CSS files needed (when I need them) so that they will replace each other. Like, for login page load login.css then for after login load app.css?
Currently I am using in the webpack.config.js the following:
{ test: /\.css$/, loader: 'style-loader!css-loader' },how to use vee-validate on vue-select tool?
I am trying to validate a select field component provided by vue-select tool using vee-validate. I tried this
<div class="form-group "> <label for="form_category ">Category <small>*</small></label> <v-select :options="categories " v-validate="'required'" data-vv-name="category" v-model="campaign.category " class="form-control " id="form_category "></v-select> </div>In the vee-validate documentation they ask to add data-vv-name="name". I added it to the parent component but the problem is that vue-select is not given any name to the input field.
Vue.js Webpack | Using some imports only in development mode
I'm using Webpack for building a vue.js application --> https://github.com/vuejs-templates/webpack
Now I wanna to import some css only in development mode. I want to import the scripts when running npm run start, but I wanna to exclude the scripts when I do a build with npm run build.
I could delete all the css imports before doing a npm run build, but is there a better solution?
Cannot find a way to wait for vue.js async function
I have the following code that works when I uncomment the "return" in fetchData below. How can I set it up so I wait for this.fetchData to finish to fill items? I have tried variants of other promises, async, await, but cannot get it to actually work...
So far I set a this.items inside fetchData but I realize it's absolutely not what I want to actually do. It shows me the first X lines of my call, because of setting it this way, but all the code that is supposed to happen after the fetchData call is bugging, starting with trying to do items.length.
import axios from 'axios'; new Vue({ el: '#app', data() { return { search: '', totalItems: 0, items: [], loading: true, pagination: {}, headers: [ //some headers ], items: [] } }, watch: { pagination: { handler () { this.getDataFromApi() .then(data => { this.items = data.items this.totalItems = data.total }) }, deep: true } }, mounted () { this.getDataFromApi() .then(data => { this.items = data.items this.totalItems = data.total }) }, methods: { fetchData() { axios.get('/api/v1/translations').then(response => { //console.log(response.data) this.items = response.data.data }) //the return below is working 100%: //return [{id:1,key:1,lg:'en',text:'woopie'}]; }, getDataFromApi () { this.loading = true return new Promise((resolve, reject) => { const { sortBy, descending, page, rowsPerPage } = this.pagination let items = this.fetchData() const total = items.length //some code to setup pagination and sort setTimeout(() => { this.loading = false resolve({ items, total }) }, 1000) }) } }, })When using Vue.js do you keep your CSS styles and JavaScripts all in the same html file?
I am new to Vue.js and am used to separating all of my files - I find it easier to read. Is this the norm when using Vue.js too or do you keep it all in the same HTML file?
vue js application using vue-router serving through node js server
I am creating an application in vue js and bundling it and then including that bundle in an html file and then serving the html file through my node server.
Now, I have made use of vue router. So, when I route to a link the browser path changes and then after that if I refresh my page, as the route is not mentioned in my root node file, error occurs. I can add the path in my root node file and serve the page but then for every route I will have to do the same and I wonder if there is something better way to solve the problem.
Hope you all understood the question. If not please ask.
How to get grouped results with SQL?
I would like the following result so I can use it in an API in Laravel:
{ type: 'Javascript', tags: [ { name: 'Vue.js', id: 10 }, { name: 'Adonis', id: 11 } ] }, { type: 'Other', tags: [ { name: 'Laravel', id: 14 }, { name: 'Phoenix', id: 15 } ] }I have the following tags table:
name (JSON) | type | idIs this possible with SQL or should I use PHP-code for this?
Thanks.
Section above draggable area
I am working with vuejs draggable/sortable, and i have 2 lists from which ican drag elements from list 1 to 2, the thing is, i can't place representative text above the list2, i mean the begin text that says something like "drag elements here", if i put that text it affects all the draggable and sortable logic inside the dragArea, how can i accomplish that without affecting the area?
<div class="row" v-if="getOptionValue == 1"> <draggable class="box" @change="elementPosition" v-model="myList" :options="{group: getSectionOptions,put:false }"> <transition-group id="list2" class="box-header with-border drop-zone" style="overflow-y: auto; height:80vh;display:block;padding:5px" name="list-complete"> <div v-for="(value, key, index) in myList" :key="key" @click.prevent="changeView(value.key,key)" v-if="value.key != 'Document'" class="panel panel-color list-complete-item"> <div class="quote box-body"> <p v-if="value.key"> <span class="spanWidth" v-if="value.key == 'line break' || value.key == 'page break'">Break</span> <span class="spanWidth" v-else>{{value.key}}</span> <span class="spanWidth text-muted" v-if="value.key == 'Table'"> (rows:{{value.rows}};cols:{{value.cols}})</span> <span class="spanWidth text-muted" v-if="value.key == 'Paragraph'">({{ value.text | truncate }})</span> <span class="spanWidth text-muted" v-if="value.key == 'Image'"> (width:{{value.width}};height:{{value.height}})</span> <span class="spanWidth text-muted" v-if="value.key == 'heading'"> ({{value.headingType}})</span> <span class="spanWidth text-muted" v-if="value.key == 'line break' || value.key == 'page break'">({{value.key}})</span> <span class="spanWidth text-muted" v-if="value.key == 'List'">(items:{{value.items.length}})</span> <span @click.stop="removeSection(index,key)" class="pull-right spanWidth"><i class="fa fa-lg fa-close"></i></span> </p> <p v-if="!value.key">{{value.description}}</p> </div> </div> </transition-group> </draggable> </div>how to distinguish the fetch host in vue-cli project
I have a question about when I build the vue-cli project,I do not know how to distinguish the http host in my code. For example:
When I debug in my local environment,My backend api url maybe the: http://localhost:3000.
When I push the code to dev server for tester,the dev backend api url maybe : http://172.110.11.12:80.
When I push the code to release environment,the release backend api url maybe:https://aaa.aa.com.
I do not want to modify the environment api url before I push the code, hot to complete it using the building config?
In node.js environment,I konw I can set the NODE_ENV to complete it,but in front-end vue-cli environment,I do not know.
is there any way to unit test a Vue.js transition
I have a Vue component with a transition with a dynamic name. I'm trying to find a way to test that the transition name is set properly based on the props I pass into the component. Here's the component.
<template> <aside :class="['cw-vue-modal', modalSizeClass]" v-show="showModal && modalName === currentModalName"> <transition :name="`${effect}-${speed}`" :duration="500"> <div class="cw-vue-modal-wrap" v-show="showModal"> <div class="cw-vue-modal-body"> <header> <h2 v-if="currentModalTitle">{{ currentModalTitle }}</h2> <a href="#" class="cw-vue-modal-close" @click.prevent="closeModal"></a> </header> <article :class="['cw-vue-modal-content', {'cw-vue-modal-pad' : padContent}]"> <slot name="content"></slot> </article> </div> </div> </transition> </aside> </template> <script> import { mapGetters, mapActions } from 'vuex'; export default { name: 'cw-modal', props: { modalName: { required: true, type: String }, padContent: { required: false, type: Boolean }, modalSize: { required: false, type: String }, effect: { required: false, type: String }, speed: { required: false, type: String, default: 'normal' }, maskLight: { required: false, type: Boolean } }, computed: { ...mapGetters(['showModal', 'currentModalName', 'currentModalTitle']), modalSizeClass() { if (this.modalSize === 'small') return 'cw-vue-modal-sm'; if (this.modalSize === 'large') return 'cw-vue-modal-lg'; return 'cw-vue-modal-md'; } }, methods: { ...mapActions(['closeModal']) } }; </script>
I'm using mocha with chia and the avoriaz library to write unit test. Here is the test.
it('it adds the slide slow effect', () => { getters = { showModal: () => true, currentModalName: () => 'my-modal', currentModalTitle: () => null }; store = new Vuex.Store({getters}); const wrapper = mount(Modal, { propsData: { modalName: 'my-modal', effect: 'slide', speed: 'slow' }, store, attachToDocument: true }); expect($('.cw-vue-modal-wrap')).to.have.class('slide-slow-enter-active'); });
It doesn't seem like the class I expect is being inserted into the dom. Any help would be great.
Thanks
unescape returned value from filters
i want to use filters to swap returned value into html checklist icon by doing like this
filters: { checkStatus: function(value){ if(value > 0){ return '<span class="bg-orange-400 text-highlight"><i class="icon-check"></i></span>' }else{ return '<span class="bg-teal-300 text-highlight"><i class="icon-cross3"></i></span>' } } }and in my table i just make it like this
<td>{{props.item.published | checkStatus}}</td>but it instead returning icon or some html tags, it just returning escaped html. so how to make it return an unescaped value? i tried to use triple curly braces but not working.
or i do it wrong? i know that i can use v-if and v-else in html too, but this way it is more cleaner and i can reuse it for other value.
grunt-contrib-uglify won't minify Vue.js beforeMount() function
My project uses Vue.js, and I'd like to minify my JS. I'm using Grunt's grunt-contrib-uglify package. My project's JS file looks like this:
// src/js/script.js var app = new Vue({ el: "...", data: {...}, computed: {...}, methods: {...}, beforeMount() {...} // line 902 });Although the un-minified code works fine, Uglify throws an error when it hits line 902. I'm guessing it's because the way beforeMount() is declared isn't standard JavaScript. If I remove it, script.js is minified no problem. Unfortunately, it's crucial to the project, and I can't think of another workaround.
I've tried using grunt --force, but it doesn't output anything.
I'd be interested in thoughts on getting Grunt to minify this, or alternatives to Grunt that do the same job. Thanks :)
Using array sort to rearrange elements in vue not working on mobile?
I'm having an issue where I'm outputting a list of components then reordering them. This works in my desktop chrome but not in mobile safari or chrome. Anyone ever run into this?
For more info, I have a vuex module that manages the entity array and I commit this mutation to reorder them:
state.entities.sort((a, b) => parseInt(a.initiative) < parseInt(b.initiative))
Then in a component, I am outputting markup according to this array of entities:
<entity v-if="showEntityList" v-for="entity in entities" :key="entity.id" :entity="entity"/>
v-bind:class data bind doesn't set value in method
I’m trying to bind a width to a div where the width is equal to a data attribute. The value of the data attribute is changing from 0 to 100, but the width of div isn’t changing. Can someone tell me why?
<div class="bar" :style="{ width: percentage + '%' }"></div> <script> export default { name: 'app', data() { return { percentage: 0, total: 43, downloaded: 0 } }, methods: { loadData() { var _this = this; this.toggleLoading(); var interval = setInterval(function(){ if (_this.downloaded == _this.total) clearInterval(interval); _this.downloaded++; _this.percentage = Math.floor(_this.downloaded / _this.total * 100) + ' %'; }, 100); }, }The dynamically created components in vue.js shows random behaviour
What i want is, there a list made from json data. When i click on a item, it creates a new list dynamically. Now when i click a different item in the first list, i want the second list to change depending on data i receive.
html structure is :
div class="subject-list container-list" id="app-1"> <item-subject v-for="item in subjectlist" v-bind:item="item" v-bind:key="item.id" > </item-subject> </div> //some other code <div class="exam-list container-list" id="app-2"> <item-exam v-for="item in examlist" v-bind:item="item" v-bind:key="item.id" > </item-exam> </div>The main.js file is :
//Dummy json data var subjects_json = { 'subjectlist': [ { id: 0, text: 'Computer Graphics' }, { id: 1, text: 'Automata Theory' }, { id: 2, text: 'Programming in C' } ]}; var exams_json = { 'examlist': [ { id: 0, text: 'IAT 1' }, { id: 1, text: 'IAT 2' }, { id: 2, text: 'Sem 2' } ]}; /*Contains definition of component item-subject... Its method() contains call to exam component because it will be called depending on the subject selected dynamically*/ Vue.component('item-subject', { props: ['item'], template: '<li v-on:click="showExams" class="subject-list-item">{{ item.text }}</li>', methods: { showExams: function(){ // alert(this.item.text) console.log("Subject Clicked: "+this.item.text) var app2 = new Vue({ el: '#app-2', data: exams_json, methods: { showStudents: function(){ console.log("exams rendered") } } }) }, } }); //Contains definition of component item-exam. Vue.component('item-exam', { props: ['item'], template: '<li v-on:click="showStudents" class="exam-list-item">{{ item.text }}</li>', methods: { showStudents: function(){ alert(this.item.text) console.log("exam component executed") // console.log("Exam Clicked: "+this.item) } } }); //Call to subject component var app1 = new Vue({ el: '#app-1', data: subjects_json, methods: { showExams: function(){ console.log("subjects rendered") } } })So what this code does is, when i click on the first list i.e. subjects list, it dynamically renders new exams list. Now when i click on second list, alert() method is called successfully. However if i click any of the subject list(first list), now the alert() is not triggered while clicking second list. Please tell me whats wrong.
Cancel draggable event without cancel sortable
i have 2 lists, list 1 and list 2, each one can be sortable, and i can just drag elements form list 1 to list 2, i am coding based on this lib:
i am trying to cancel the draggable event when i drag a element from list 1 to a invalid zone, i can detect when i am inside the valid zone or not, but i can't cancel the event.
I tried with return false on the move function, but instead it cancels also my sortable events on my list1, any help on how to accomplish this?
i have a lot of code it is useless to share it since it is to much at the moment and is all conected, but in the pens on the github page it doesn't cancel to, any help with this?
how to share data between components in VUE js (while creating list)
Could you please tell me how to share data between components in VUE js (while creating list).I have two components list components and add todo component.I want to add items in list when user click on add button.But issue is input field present in different component and list is present in different component here is my code https://plnkr.co/edit/bjsVWU6lrWdp2a2CjamQ?p=preview
// Code goes here
var MyComponent = Vue.extend({ template: '#todo-template', props: ['items'] }); var AddTODO = Vue.extend({ template: '#add-todo', props: ['m'], data: function () { return { message: '' } }, methods: { addTodo: function () { console.log(this.message) console.log(this.m); //this.m =this.message; }, }, }); Vue.component('my-component', MyComponent); Vue.component('add-todo', AddTODO) var app = new Vue({ el: '#App', data: { message: '', items: [] }, });flexbox with vue js not working
Could someone please tell me what is wrong with this simple code? Just starting to explore flexbox. It works well on a normal html but once I vuejs-ed it, the footer stays on the top of the screen as if there isn't flex css.
Thank you.
<template> <div id="app"> <div class="wrapper"> <p>THIS IS MY CONTENT</p> </div> <footer> This is the footer </footer> </div> </template> <script> export default { name: 'app', data () { return { msg: 'Welcome to Your Vue.js App' } } } </script> <style lang="scss"> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; /* added as per LGSon's suggestion */ height: 100%; flex-grow: 1; display: flex; flex-direction: column; } html, body { height: 100%; margin: 0; } body { display: flex; flex-direction: column; } .wrapper { flex: 1 0 auto; } footer { background: #ccc; padding: 20px; } </style>How to add items in list on button click?
Could you please tell me how to add an item to list on button click. Here is my code
https://plnkr.co/edit/hVQKk3Wl9DF3aNx0hs88?p=preview
var AddTODO = Vue.extend({ template: '#add-todo', props: ['m'], data: function () { return { message: '' } }, methods: { addTodo: function () { console.log(this.message) console.log(this.m); //this.m =this.message; }, }, }); <template id="add-todo"> <div> <input type="text" v-model="m"> <button @click="addTodo">Add todo</button> </div> </template>is there any way to add items