Vuejs

Subscribe to Vuejs feed
most recent 30 from stackoverflow.com 2017-09-14T21:10:11Z
Updated: 7 years 1 week ago

vue.js - Dynamically render items on scroll

Sun, 2017-09-03 21:02

I have list of 100+ items and rendering takes too much time.

I am therefore rendering just empty DIV's with specific height (to reserve the space) and want to render the content when it becomes visible (that means document on scroll).

So, in this code below all 3 items are rendered. BUT the last two items should be blank and its content should be rendered once when they become visible.

What's the best approach?

var myItems = [{name: 'New item'}, {name:'Another'}, {name:'Third'}]; new Vue({ el: '#app', data: { items : myItems } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script> <div id="app"> <div class="items" v-show="items.length"> <div v-for="item in items" style="border:2px solid red;height:700px"> <!-- following content should be rendered only when the item becomes visible --> <div class="content-when-visible">{{ item.name }}</div> </div> </div> </div>

Categories: Software

Vue JS 2: Bind computed property to data attribute

Sun, 2017-09-03 20:57

I have a data object in Vue.js 2 that looks like this:

data: { items: [ { value1: 10, value2: 10, valuesum: "" }, { value1: 10, value2: 100, valuesum: "", } ]

I render that data object in a table and run calculations on it. I want the valuesum property to be computed and stored in each object somehow. In other words, I want the code to essentially perform this:

data: { items: [ { value1: 10, value2: 10, valuesum: {{ value1 + value2 }} //20 }, { value1: 10, value2: 100, valuesum: {{ value1 + value2 }} //110 } ]

The computed attribute doesn't seem to be able to accomplish this. I tried to use the following function but this does not work:

function (index) { for (let i = 0; i < this.items.length; i++ ){ return this.items[index].value1 + this.items[index].value2; } }

The closest I have managed to get to an answer is by doing the calculation inline, but I can't bind its result to the items.total object. My HTML looks like this:

<table id="table"> <thead> <tr> <td>Value 1</td> <td>Value 2</td> <td>Sum</td> </tr> </thead> <tbody> <tr v-for="item in items"> <td><input type="number" v-model="item.value1"></td> <td><input type="number" v-model="item.value2"></td> <td> {{ item.value1 + item.value2 }} </td> </tr> </tbody> </table>

But I can't add v-model to it, since it's not an input. I'd like to avoid adding a readonly <input> to the column, since that doesn't seem like the best solution and isn't very elegant.

Categories: Software

vue select doesn't show initial value

Sun, 2017-09-03 20:48

I am trying to show the initial value of a array of objects like this:

tableStyes[ {Id: 1, style: "blabla1}, {Id: 2, style: "blabla2"} ]

basicly i am using a computer method to give me the array from vuex store

tableStyles () { return this.$store.getters.getTableStyles },

i am doing the select this way:

<select class="form-control" v-model="table.tableStyle"> <option v-for="(item,key) in tableStyles" :value="item.Id"> {{ item.style }} </option> </select>

i want to get the value based on the id, i mean i want to get the text associated to the id, and the id is table.tableStyle, that is 1 at the begin that should be the selected item, but somehow it doesn't work :/.

Any help?

Categories: Software

How to send data to component in vue js?

Sun, 2017-09-03 18:48

How to send data to a component in vue js ? I got data/response from the server on button click.Now I want to send this response to component and display on list using v-for. 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) { Vue.http.get('data.json').then(function(response){ alert('dd') }, function(error){ console.log(error.statusText); }); } } }) 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: {}, });
Categories: Software

Return multiple values from a computed filter in Vue JS

Sun, 2017-09-03 18:19

I have a search box where when the user inputs an artist name and it shows a list of artists that match the user input.

I want to display the artist image next to the artist name in the search.

I have an object that contains the following. Artist Name as key and path to image as value

Radiohead: 'path_to_image', Elliott Smith:'path_to_image'

I have a computed property that filters the artists name for search.

computed: { filteredArtists() { return Object.keys(this.artistsList).filter((artist) => { return artist.match(this.artistName) }) }

},

and in my template I'm iterating throgh the values

<ul class="searchFliter" v-for="artist in filteredArtists"> <li v-text="artist"></li> </ul>

I can't find a way to manage that with computed values. I can easily iterate over my object and display both Artist name and Artist image but can't filter it.

Thanks in advance

Categories: Software

Vue router for multiple navigations

Sun, 2017-09-03 17:40

I am using vuejs router as frontend for my app which is getting deeper and deeper day by day. Now my client has asked me to create a new section for my site which basically is a complete website in its nature. hence will have a different navigation. Now my question is how do i make it happen.

one solution is to use a variable or something to hide the main navigation and show this sub-navigation bar. This doesn't feel neat to me. ' I open to any suggestions.

Categories: Software

array copy keeps changing without edition

Sun, 2017-09-03 17:37

I am working on a simple list builder, i can create and edit the list, basicly i have a modal where i build the list after that i can edit it, my issue is if i edit and change the number of items inside the list without pressing the edit, the changes to the list apply. all the rest that i change and don't press edit, works well.

Here is a example:

my modal edition:

data () { return { newItem: '', listItem: 0, showNewItem: false, bulletList: { currentSymbol: '•', key: 'List', items: [ ], ordered: false, numbering: 38 }, listOptions: [ { 'symbol': '•', 'number': 37 }, { 'symbol': '1', 'number': 1 } ] } },

in my edition the only thing that can change is the bulletList object, so when i press the edition section it loads the object like this:

mounted () { console.log('MOUNTED', this.bulletList.items) var sectionKey = this.$store.getters.getCurrentEditionKey this.bulletList =_.clone(this.$store.getters.getDocumentAttributes[sectionKey]) }

when i add a item to edit my bulletList and close the configuration modal it added(it shouldn't) the only thing i do when i add a new item is to push it to the local object inside my component, and not the one that i copied from vuex store, strange issue any help? it has something to do with the array behaviour?

removeItem () { this.bulletList.items.splice(this.listItem, 1) this.listItem = 0 }, addNewItem () { this.bulletList.items.push(this.newItem) this.newItem = '' },
Categories: Software

how to avoid JSON source replication for multiple inputs with same autocomplete source

Sun, 2017-09-03 16:55

I have multiple inputs' (dynamically created) with the same easyautocomplete source. The thing is that each input brings its own copy data.json file over the net.

is there a way to cache the data.json file and use the same source instead of creating network overhead?

the attached JS code is in the created lifecycle hook of the vue container.

$(document).ready(function() { $("body").find(".autoComplete").each(function() { var $input = $(this); var $url = $(this).data("url"); var options = { url: "./data.json", getValue: "Shortcut", list: { maxNumberOfElements: 10, onSelectItemEvent: function() { var value = $input.getSelectedItemData().Name; $input.val(value).trigger("change"); }, onChooseEvent: function() { var value = $input.getSelectedItemData().Name; $input.val(value).trigger("change"); //TAB emulation when pressing enter var inputs = $(':input').keypress(function(e) { if (e.which == 13 && this.value) { e.preventDefault(); var nextInput = inputs.get(inputs.index(this) + 1); if (nextInput) { nextInput.focus(); } } }); }, match: { enabled: true } }, theme: "square" }; $input.easyAutocomplete(options); }); }); <template lang="html"> <div> <tr> <td> <input type="text" v-model.lazy="herb.name" @blur="addRow" class="autoComplete" placeholder=""> </td> <td> <input type="number" v-model.number.lazy="herb.quantity" placeholder=""> </td> </tr> </div> </template>

Categories: Software

How to fetch data from server in vue js?

Sun, 2017-09-03 16:16

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: {}, })

;

Categories: Software

Load CSS Dynamically according to module loaded with Webpack - VueJS

Sun, 2017-09-03 15:43

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' },
Categories: Software

how to use vee-validate on vue-select tool?

Sun, 2017-09-03 15:34

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.

Categories: Software

Vue.js Webpack | Using some imports only in development mode

Sun, 2017-09-03 15:32

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?

Categories: Software

Cannot find a way to wait for vue.js async function

Sun, 2017-09-03 15:31

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) }) } }, })
Categories: Software

When using Vue.js do you keep your CSS styles and JavaScripts all in the same html file?

Sun, 2017-09-03 14:46

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?

Categories: Software

vue js application using vue-router serving through node js server

Sun, 2017-09-03 14:06

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.

Categories: Software

How to get grouped results with SQL?

Sun, 2017-09-03 13:11

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 | id

Is this possible with SQL or should I use PHP-code for this?

Thanks.

Categories: Software

Section above draggable area

Sun, 2017-09-03 10:18

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>
Categories: Software

how to distinguish the fetch host in vue-cli project

Sun, 2017-09-03 04:49

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.

Categories: Software

is there any way to unit test a Vue.js transition

Sun, 2017-09-03 04:47

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

Categories: Software

unescape returned value from filters

Sun, 2017-09-03 02:57

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.

Categories: Software

Pages