Feed aggregator

Duplicate registration of components in Vue.js

Vuejs - Mon, 2017-09-04 04:22

If i had a repository which held all of my Vue components, and a system by which my other codebases could pull in the components they required from this Vue repo.

I have 2 components, 1 of which is used as a child in the other but can also be used in a standalone fashion. Because I'd like for there to be minimal implementation knowledge needed for the use of these components, I'd like to import the child in the parents script as such

<template> <child-component></child-component> </template> <script> import childComponent from 'path/to/child/child-component.vue' export default { name: 'parent-component', components: { 'child-component': childComponent } } </script>

Doing this will register the child-component in the parent's scope and it can't be used outside of that scope. So if I need to now use child-component as a standalone component I'll also need to register it in the global scope in the base JS file, where I'm importing vue components into as such:

import Vue from 'vue'; import childComponent from 'path/to/child/child-component.vue'; import parentComponent from 'path/to/parent/parent-component.vue'; function registerComponents() { Vue.component(childComponent.name, childComponent); Vue.component(parentComponent.name, parentComponent); } function initVue() { registerComponents(); new Vue({ el: '#vue-app' }); } window.addEventListener('load', initVue);

My question is thus, if I were to register childComponent with parentComponent and then again with the global scope, is Vue smart enough to sort this out or will my compiled JS have the code duplicated.

If the code is in fact duplicated and childComponent was listening for events, what would happen if the event occurred?

Categories: Software

how to set the data object in a vue-resource such that it won't error in console

Vuejs - Mon, 2017-09-04 01:19

I am learning Vue this weekend so a very simple question.

I'm trying to convert some jQuery to using Vue with vue-respource. I am getting back data for a location with items. The problem I'm having is that whenever I load this object, I get an error saying the location is null (which is what I set it to be in data. What is the proper way to do this? Should I have a guard statement to prevent it rendering through items? If it was an array of locations, I could set to an empty array but for a single object, it seems like should be null. How best to have an empty data object that is filled via an async call?

const Location = { data(){ return {location: null } }, template: `<div>{{location.name}} <div v-for="item in location.items"> <div>{{item.id}}</div> </div> </div>`, created(){ this.fetchData(); }, methods: { fetchData(){ this.$http.get('/arc/api/v1/site_admin/locations/' + this.$route.params.id + '/dashboard').then((response) => { console.log(response.data); this.location = response.data.location }).catch( error => { console.log(error); }); } } }
Categories: Software

Rails Webpacker Vue '__webpack_require__(...) is not a function' Error

Vuejs - Sun, 2017-09-03 23:26

I'm getting this error after I run '/bin/webpack-dev-server' and make any changes to .vue files. When I first run the server everything works fine, it's only after I make changes that this error gets thrown. On a side note changes to the hello_vue.js file do not flash this error and they do show.

The files gets recompiled successfully in the system terminal too when the dev-server is running. I've added nothing out of the ordinary to the application as this is a new project.

The guide at https://github.com/rails/webpacker was used to get webpacker up and running.

Could this be a turbolinks error?

Any help is appreciated!

hello_vue.js

import Vue from 'vue/dist/vue.esm' import App from './app.vue' document.addEventListener('DOMContentLoaded', () => { const app = new Vue({ el: '#hello', data: { message: "Can you say hello?" }, components: { App } }) })

app.vue

<template> <div id="app"> <center> <p>{{ message }}</p> <button type="button" name="button" @click="addOne">Click me!</button> <p>This is a number test: {{ data }}</p> </center> </div> </template> <script> export default { data: function () { return { message: "Hello Vue! From inside app.vue!", data: 5 } }, methods: { addOne(){ this.data += 1 console.log(this.data) } } } </script> <style scoped> p { font-size: 2em; text-align: center; } </style>

package.json

{ "dependencies": { "@rails/webpacker": "^3.0.0", "vue": "^2.4.2", "vue-loader": "^13.0.4", "vue-template-compiler": "^2.4.2" }, "devDependencies": { "webpack-dev-server": "^2.7.1" } }

consoler debugger:

exports = module.exports = require("../../../node_modules/css-loader/lib/css-base.js")(undefined); // imports // module exports.push([module.id, "\np[data-v-13f0f5d2] {\n font-size: 2em;\n text-align: center;\n}\n", ""]); // exports ////////////////// // WEBPACK FOOTER // ./node_modules/css-loader!./node_modules/vue-loader/lib/style-compiler?{"vue":true,"id":"data-v-13f0f5d2","scoped":true,"hasInlineConfig":false}!./node_modules/vue-loader/lib/selector.js?type=styles&index=0!./app/javascript/packs/app.vue // module id = 0 // module chunks = 0

browser console:

<anonymous> webpack-internal:///0:1:28 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:75:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> webpack-internal:///47:5:16 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:628:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> webpack-internal:///46:5:3 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:616:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> webpack-internal:///45:3:21 <anonymous> webpack-internal:///45:1:29 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:604:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> webpack-internal:///44:1:14 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:592:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> webpack-internal:///34:5:14 <anonymous> webpack-internal:///34:1:29 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:475:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:1209:1 __webpack_require__ http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:20:12 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:63:18 <anonymous> http://localhost:3000/packs/hello_vue-4d561ea1e57c869e7983.js:1:11
Categories: Software

How to pass changed value to other component's methods in Vue.js?

Vuejs - Sun, 2017-09-03 21:03

In the header component, let's call it App.vue, there is a select element:

<select v-model="locale"> <option value="en">English</option> <option value="pl">Polski</option> </select>

In the same component, the option selected by user gets processed in watch:

watch: { locale (val) { this.$i18n.locale = val; console.log("locale: ", val); localStorage.setItem("userPrefLang", val); } },

How can I notify other components (siblings, not children), let's say Users.vue, that the locale parameter was changed? I'd like to pick up the new value in the code (using a JS method), not with bound DOM elements. The new value should trigger the page reload due to changed locales. Should I use Users.vue's watcher, props, or is there any other way?

Categories: Software

vue.js - Dynamically render items on scroll

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

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

Vuejs - 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?

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

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

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

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

Vuejs - 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?

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

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?

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

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

Vuejs - 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?

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

Vuejs - 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?

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

Pages