Software
Load nested JSON array into select in Vue using computed function
Originally in my Vue component I had a series of nested if statements that would go through the JSON data to determine whether a text input should be displayed or a select based on a has_selectable_value option being true (select display) or false (text input display), and if it was a select then loop through the data and output associated options.
I have been able to change that to a computed statement which almost does everything I need it to do apart from one little thing which is to display the select options.
Here is the relevant part of the Vue Code:
<template v-else-if="searchtype == 9"> <select v-for="service in selectableServices" class="form-control" v-model="searchvalue" required> <option value="">Select A Location</option> <option v-for="sl in selectableLocations" :value="sl.location_id">{{sl.name}}</option> </select> <input v-for="service in nonSelectableServices" class="form-control" v-model="searchvalue" placeholder="Enter Search Value" required> </template>The current computed functions:
services: function () { var ret = [] this.countries.forEach(function(country) { country.states.forEach(function(state) { state.services.forEach(function(service) { ret.push(service) }); }); }); return ret; }, selectableServices: function () { return this.services.filter(service => service.id == this.service && service.has_selectable_location); }, nonSelectableServices: function () { return this.services.filter(service => service.id == this.service && !service.has_selectable_location); }, selectableLocations: function () { // Filter one more level down return this.selectableServices.map(service => service.selectablelocations); },This is the JSON data structure I am working with as well (I cut it back to the relevant parts for this part of the code):
[ { "id": 1, "name": "Country Name", "states": [ { "id": 1, "name": "State Name", "services": [ { "id": 1, "name": "Service Name", "has_selectable_location": 1, "selectablelocations": [ { "id": 1, "name": "Selectable Location A", }, ] } ] } ] } ]Using a Vue plugin for Chrome I can see that the computed function selectableLocations loads an array containing the individual locations, but the existing v-for statement isn't able to function correctly. Instead I still need to go down one more level which I can do by adding an extra v-for loop like so:
<template v-for="selectableLocationsList in selectableLocations" > <option v-for="sl in selectableLocationsList" :value="sl.location_id">{{sl.name}}</option> </template>Everything displays correctly, but I am not sure if this is best practice as I was hoping to do as much of this in a computed function as possible and ideally only require a single v-for statement. But if it's not possible like that I understand and I can leave it as is.
Thank you in advance.
Conventions project with PHP and VueJs?
Basically I don't know how to start implementing VueJs into my project. Should I use a CDN or require it via NPM? NPM would make it easier to implement VueJs packages.
I have in (my own framework (for learning)) a path /public/ in which a index.php file is located, along with an assets folder (which leads is followed css/js folders).
So the question is, what would you recommend, and how would you implement routing etc.?
Vue.js static hosted single-page app
I would like to use vue.js, and compile everything to a static site on Amazon S3. This seems to be possible with Nuxt, but it seems to generate separate HTML files for your routes. Is it not possible to generate a single-page static app with vue.js?
How to load scss in vue.js
//Vuejs component
<template> <form class="form form--login" v-on:submit.prevent="login"> <h2 class="form__title">Login</h2> <div class="info info--error" v-if="infoError">Login failed. Please try again.</div> <div :class="{'is-waiting': loader}"> <div class="form-block"> <input v-model.trim="username" class="field" name="username" type="text" placeholder="User ID" required> </div> <div class="form-block"> <input v-model.trim="password" class="field" name="password" type="password" placeholder="Password" required> </div> <div class="form-block form__actions"> <router-link to="/password-reset">Lost your password?</router-link> <button class="button button--green form__submit">Login</button> </div> </div> </form> </template> <script> <style lang="scss" type="text/scss"> .is-waiting { position: relative; transition-duration: .3s; > * { opacity: .25; } &:before { content: ''; height: 100%; left: 0; position: absolute; top: 0; width: 100%; z-index: 9; } &:after { background: { position: center; size: cover; } content: ''; height: 64px; left: 50%; position: absolute; top: 50%; transform: translate(-50%, -50%); width: 64px; } } </style>//webpack.config
"dependencies": { "onsenui": "^2.5.1", "node-sass": "^4.5.0", "sass-loader": "^5.0.1", "vue": "^2.4.2", "vue-onsenui": "^2.1.0", "vue-resource": "^1.3.4", "vuex": "^2.3.1" },My component still doesn't load style correctly.
Please help!!
Use VueProgress in Store.js
I have imported it and initialized it in my store.js(vuex) file.
Why Can't i use it for a function in store that requests a http.
Error -> Cannot read property 'start' of undefined
function something(state){ Vue.Progress.start(); Vue.http.get('https://something.com/abc.json') .then(response=>{ Vue.Progress.finish(); return response.json(); },response=>{ Vue.Progress.fail() }) .then(route=>{ console.log(route); }) }How can i use it in my store.js
I can perfectly use it in my .vue components by -> this.$Progress.start() & <vue-progress-bar></vue-progress-bar> in template ,
for here , i am placing <vue-progress-bar></vue-progress-bar> in App.vue(main-component)
view progress to http.get() query (by vue-resource) from firebase
This is my query by http.get() method (using vue-resouce) from firebase database.
How can i see my progress in console(in %).
Triggering child method (or computed property) from root - vue2
In nested object, my computed property in my component doesn't track changes well, so computed property doesn't get triggered as expected. Instead, I want to trigger it in the from parent.
What is the proper way of executing a method, preferably this computed method from my root?
I tried using
this.$emit('updated'); on root method
this.$parent.$on('updated', this.organise); and catch it like this,
but this returns me an error:
Error in event handler for "updated": "TypeError: Cannot read property 'apply' of undefined"
How to add a div id to each element in a v-for list?
Here is my Vue
<div class="drag"> <h2>List 1 Draggable</h2> <ul> <li v-for="category in data"> <draggable v-bind:id="category" v-model="category" :move="checkMove" class="dragArea" :options="{group:'items'}"> <div v-for="item in category" style="border: 3px;">${ item.name }</div> </draggable> </li> </ul> </div> </div> <script> var vm = new Vue({ el: "#main", delimiters:['${', '}'], data: {{ data | tojson | safe }}, methods:{ checkMove: function(evt){ return true } } });I want each of the div in my v-for to have an id. Based on this; https://vuejs.org/v2/guide/list.html
I think I need something like v-bind:key="category.id" in the li tag (the one with the v-for. That makes my div id [Object object][Object object][Object object].
I think this is for each of the items in my category. I would like to add a div id to each category as well as a div id to each item in category. These should be something like "category.name" (the name of the category, so uncategorized, and "item.name" in the item itself. My data object looks like this:
{"data": {"uncategorized": [{"id": 0, "name": ""}, {"id": 1, "name": "first"}, {"id": 2, "name": "another"}]}}
How to pick v-model for Vue.js draggable when using a nested list
Here is my Vue
<div id="main"> <h1>Vue Dragable For</h1> <div class="drag"> <h2>List 1 Draggable</h2> <ul> <li v-for="category in data"> <draggable id="category" v-model="category" :move="checkMove" class="dragArea" :options="{group:'people'}"> <div v-for="item in category" style="border: 3px;">${ item.name }</div> </draggable> </li> </ul> </div> </div> <script> var vm = new Vue({ el: "#main", delimiters:['${', '}'], data: {{ data | tojson | safe }}, methods:{ checkMove: function(evt){ console.log(evt.draggedContext.index); console.log(evt.draggedContext.futureIndex); console.log(evt.from.id); console.log(evt.to.id); axios.post('/categorize', { 'index': JSON.stringify(evt.draggedContext.index), 'futureIndex': JSON.stringify(evt.draggedContext.futureIndex), 'from':evt.to.id, 'to':evt.from.id, }); return true } } }); </script>the data rendered in the template {{ data | tojson | safe }} just looks like:
{"data": {"uncategorized": [{"name": ""}, {"name": "first"}, {"name": "another"}]}}Right now I am getting this error
You are binding v-model directly to a v-for iteration alias. This will not be able to modify the v-for source array because writing to the alias is like modifying a function local variable. Consider using an array of objects and use v-model on an object property instead.
so I don't think it it likes how I am using v-model. I am basing my code on this example: https://jsfiddle.net/dede89/32ao2rpm/ which uses raw son names in its v-model tags, but I cannot do that. So how should I do this? Thanks!
VueJS: Uncaught SyntaxError: Unexpected token import
thanks for reading this. I am building a web app using vuejs and flask as server. Do you guys have any recommendation for why it does not recognize "import"? im trying to use this.$http.get . why it is not recognizing it? thanks in advance
import Vue from 'vue' import VueResource from 'vue-resource' Vue.component( 'button-labels', { props : ['labelbtn'], template : `<div class="button-container"><button class="button-app" v-for="label in labelbtn" v-on:click="clickHandler(label)" >{{label.label}}</button></div>`, methods : { clickHandler : function(label) { if (label.id === 1) { this.$emit('event_child', 'search-template') } }, } }) Vue.component( 'search-template', { props: ['searchdata'], data : { entries : [] }, template : `<div><input class="searchBar"><div class="response-list"><button class="entries"></button></div> <audio class="audio" controls></audio><button class="button-back" v-on:click="backHandler"> Return</button></div>` , methods : { backHandler : function(){ this.$emit('event_child', 'button-labels'); }, }, created : function(){ this.$http.get('https://google.com', (data) => { console.log( data ); }) .error((err) => console.log(err)) }, }) new Vue({ el: '#app', data : { labels : [ { id : 1, label : "Search" } , { id : 2, label: "Categories" }, { id : 3, label: "Favorites" }, {id : 4, label: "Settings"} ], currentView : "button-labels", }, methods : { eventChild : function(label) { this.currentView = label; } } })this is my package.json
{ "scripts": { "transpile-es2015": "babel src -d lib" }, "devDependencies": { "babel-core": "^6.1.2", "babel-loader": "^6.1.0", "babel-plugin-transform-runtime": "^6.1.2", "babel-preset-es2015": "^6.1.2", "babel-runtime": "^6.0.14", "css-loader": "^0.21.0", "style-loader": "^0.13.0", "vue-hot-reload-api": "^1.2.1", "vue-html-loader": "^1.0.0", "vue-loader": "^7.0.1", "webpack": "^1.12.3", "webpack-dev-server": "^1.12.1" }, "dependencies": { "bootstrap": "^3.3.5", "vue-resource": "^0.1.17", "vue-router": "^0.7.5", "vue": "^1.0.7" } }
Watching changes on an object in vue
I have a object named accounts and it hold information in this structure:
{ 1: { 'x': [ [], [], [] ], 'y': [ [], [] ], }, 2: { 'x': [ [], [] ], 'z': [ [] ], }, }In my root, in data, it is stored.
Now I want to create another variable, watching this variable, and when new elements added or removed from this accounts variable, change my new variable and put it in the right format. This is how I want it to be:
{ 1: { 'x': [ [] ], 'y': [ [] ] }, 2: { 'y': [ [] ], 'z': [ [] ] } }And when the letter level is added or removed, I want to add/remove from this watcher variable too.
new Vue({ el: '#root', data: { accounts: {}, watcher: {} }, methods: { changeHappened() { // values appended to accounts / changes applied // now how does the watcher object gets the wanted structure // and add/remove if new items added/removed } } })Where is the best place to add this watcher and watch modifications on accounts object?
Sublime Text 3 cannot parse symbols from vuejs
In Sublime Text, I'm used to accessing function names through the @ symbol list. However, when using a project established from https://github.com/vuejs-templates/webpack, all the function names and data attributes in .vue files do not appear in this list. This makes navigating .vue files rather tedious. I have installed all vue-related Sublime packages but none of them seem to fix this. Is there any way to get back symbol indexing working properly in this context ? Or, do you have any experience with other text editors that do this properly?
Vuetable-2 grid/tiles view
I have created a table using vuetable-2 and now I would like to see the table in “tiles” view. What I'm looking to do is to see each row on his own "tile". As it is right now I don't have access to the and components. Any help would be much appreciated.This is my code:
<template> <div class="ui container-fluid"> <vuetable ref="vuetable" api-url="https://phpserver-alfre-85.c9users.io/query_pets.php" :fields="fields" pagination-path="" @vuetable:pagination-data="onPaginationData" ></vuetable> <template></template> <vuetable-pagination ref="pagination" @vuetable-pagination:change-page="onChangePage"></vuetable-pagination> </div> </template> <script> import Vuetable from 'vuetable-2/src/components/Vuetable' import VuetablePagination from 'vuetable-2/src/components/VuetablePagination' export default { components: { Vuetable, VuetablePagination }, data () { return { fields: [ { name: 'image', title: 'image ⇅' }, { name: 'name', title: 'name ⇅' }, { name: 'breed', title: 'species ⇅' }, { name: 'age', title: 'age ⇅' }, ] } }, methods: { onPaginationData (paginationData) { this.$refs.pagination.setPaginationData(paginationData) }, onChangePage (page) { this.$refs.vuetable.changePage(page) } } } </script> <style> </style>Dynamically create select options
I have 2 selects, one with data and other one empty. When first one is selected, I catch it using a switch. Now, depending on the value, I want to create option elements and put them inside empty select.
Let's say I have an array of values
var values = ['Hello', 'world', 'etc']When selected
selected(event) { var name; switch (event.target.value) { case 'roth': // append values as options into select, using foreach // such as: // <option name="hello"></option> ... } }This is select in my template:
<select class="form-control" :id="selection"> <option selected="" disabled="" value="0"></option> </select>Vue children wont work
heres my app.js
{ path: '/superadmin', component: require('./components/Superadmin/Home.vue'), children: [ { path: 'users', component: require('./components/Superadmin/Users.vue'), }, ] }heres my Users.vue
<template> <div class="d-flex"> <div class="p-2 col-4"> <b-card> <b-form-fieldset label="Username"> <b-form-input v-model="username"></b-form-input> </b-form-fieldset> <b-form-fieldset label="Password"> <b-form-input v-model="password"></b-form-input> </b-form-fieldset> <b-form-fieldset label="Confirm Password"> <b-form-input v-model="confirm_password"></b-form-input> </b-form-fieldset> <b-button variant="success">Submit</b-button> </b-card> </div>
heres my home.vue
<template> <div> <nav-bar></nav-bar> </div> </template>and here/s my url http://localhost:8000/#/superadmin/users
my childer wont render the user.vue page i dont know whats the problem with my code can some please help me please its 3:30am here in the Philippines and my so tired of my code not working please comment your answers so i can continue with my project please oh please thank you in advance for answering
How to render flask jinja2 objects in a vuejs v-for draggable list?
Here is my Vue
<div class="drag"> <h2>List 1 Draggable</h2> <draggable id="cat1" v-model="list" :move="checkMove" class="dragArea" :options="{group:'people'}"> <div v-for="element in list">${ element.name }</div> </draggable> <h2>List 2 Draggable</h2> <draggable id="cat2" v-model="list2" :move="checkMove" class="dragArea" :options="{group:'people'}"> <div v-for="element in list2">${ element.name }</div> <p>another</p> </draggable> </div> <script> var vm = new Vue({ el: "#main", delimiters:['${', '}'], data: { list: [{ name: "John" }, { name: "Joao" }, { name: "Jean" }], list2: [{ name: "Juan" }, { name: "Edgard" }, { name: "Johnson" }] } } </script>This works great. The data from the list shows up properly and is draggable. Now I want to pass the following dict into the data object from flask so that I can render that instead.
The object when rendered with just {{ data }} looks like:
{u'uncategorized': [{'name': u''}, {'name': u'first'}, {'name': u'another'}]}so you can see its about the same format as the object that gets passed into data:
{ list: [{ name: "John" }, { name: "Joao" }, { name: "Jean" }], list2: [{ name: "Juan" }, { name: "Edgard" }, { name: "Johnson" }] }But when I try and just substitute in data: {{ data }} in the vue, it doesn't render properly.
So what do I have to do to the data object in flask to make Vue "accept" it?
Using laravel old function within a vuejs component
I have a vuejs component that contains a form, I want to use the laravel old function so I'm able to repopulate the input fields if the form validation fails.
My guess would be I'd need to do something like pass the old function in as a prop to the component possibly but not sure if this is the 'right' way of doing it.
I'm just looking for confirmation on the best way of doing this.
Populate HTML template with $http response VueJS
I am new to VueJs and working on a small nutrition app. Currently, we want to make food recs based on certain nutrients.
The JS is as follows:
recommendFood: function() { this.recs = {}; var _this = this; var getItem = function(ndbno,i,nid) { _this.$http.get('http://127.0.0.1:3000/item?ndbno=' + ndbno).then(function(response) { var someData = response.body; var nutrients = someData.report.food.nutrients; var item = someData.report.food; item = this.addNutrientsToItem(item, nutrients); this.recs[nid].push(item); }); }; for (var i=0; i<this.low_nutrients.length; i++) { this.low_nutrients[i].recs = []; this.recs[this.low_nutrients[i].id] = []; for (var k=0; k<this.low_nutrients[i].food_map.length; k++) { var ndbno = this.low_nutrients[i].food_map[k]; getItem(ndbno,i,this.low_nutrients[i].id); } } console.log(this.recs) }
I want this.recs to be an object with attributes that are equivalent to a nutrient id (that we store). Each nutrient has a food_map array attached to the object that contains id's of foods that would be the recommendations. I need to send those id's (ndbno) to the http request to receive the object of that food recommendation (item).
The this.recs object actually populates correctly (despite there probably being a better way to write my code), however since it's waiting on the loop and promise, the html renders before the object is complete. Therefore, my html is blank. How can I display the recs on the html once they are updated on the promise result?
Here is my HTML:
<div v-for="(nutrient, idx) in low_nutrients"> <h2>{{nutrient.name}}</h2> <div>Recommended Foods:</div> <div> <div>Recs:</div> <div v-for="rec in recs[nutrient.id]">{{rec}}</div> </div> </div>
The desired object this.recs should look something like this (and it does show this in the console):
this.recs = { 291: [{},{},{}], 316: [{},{},{}] }
Bind HTML tag to data or prop
Is it possible to bind an HTML tag (element) to the value of a data or property in Vue 2?
I tried different syntaxes but couldn't get any to work, and googling didn't help.
Here are two of the syntaxes I tried:
Direct 'string' interpolation:
<{{ someProp ? 'button' : 'a' }}> <!-- Some complex template I want to keep DRY --> </{{ someProp ? 'button' : 'a' }}>v-bind the tag on a template element (hopeful guess):
<template :tag="someProp ? 'button' : 'a'"> <!-- Some complex template I want to keep DRY --> </template >If that's not possible, how can I avoid duplicating the content and attributes of the element just to change the associated HTML tag? What I want to avoid is:
<button v-if="someProp" /* Some attribute bindings */> <!-- Some complex template I want to keep DRY --> </button> <a v-else /* Repeating the above attribute bindings */> <!-- Repeating the above template, breaking the DRY principle --> </a>How to save and retrieve file using pouchdb and vue js
Can someone help me on how to upload a file on pouchdb and display those uploaded files on page. I want to upload a file including name info of that file. When I check the fetch files using the console I can see [object object]. Am I doing the right thing? Any advice is well appreciated. Here is my code.
//Notes.vue // By the way Im using onsen ui for this <template> <v-ons-page> <v-ons-list> <v-ons-list-header>Auditing</v-ons-list-header> <v-ons-list-item v-for="note in notes"> <div class="left"> <img src="" alt=""> </div> <div class="center"> <span>{{ note._attachment['files'].data }} File here</span> </div> </v-ons-list-item> </v-ons-list> // Customize form for uploading file and info <v-ons-alert-dialog modifier="rowfooter" :visible.sync="dialogVisible" > <span slot="title">Create a Note</span> //File name of the file <v-ons-input float placeholder="Name of note" v-model="name" > </v-ons-input> // File <v-ons-input type="file" @change="onFileChange"></v-ons-input> <v-ons-button @click="addNotes(name)">Submit</v-ons-button> </v-ons-alert-dialog> </v-ons-page> </template>//Here the methods for uploading and reading file uploaded
<script> import PouchDB from 'pouchdb' var db = new PouchDB('reviewerdb') export default { data() { return { dialogVisible: false, notes: [], file: '', name: '', path } }, mounted() { this.getNotes(); print('notes: ' + this.notes); },//Methods just adding a desciption
methods: { onFileChange(event) { this.file = event.target.files[0]; }, addNotes() { db.put({ _id: 'notes', _attachments: { "file": { type: this.file.type, data: this.file } } }) }, getNotes() { db.get('notes', {attachments:true}).then(function (note) { this.notes = note; }); } } }