Vuejs

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

Dependency Tracking function in JS

Thu, 2017-09-14 12:38

At Vue.js Advanced Features from the Ground Up Evan gave a little task.

  • Create a Dep class with two methods: depend and notify.
  • Create an autorun function that takes an updater function.
  • Inside the updater function, you can explicitly depend on an instance of Dep by calling dep.depend()
  • Later, you can trigger the updater function to run again by calling dep.notify().

The full usage should look like this:

const dep = new Dep() autorun(() => { dep.depend() console.log('updated') }) // should log: "updated" dep.notify() // should log: "updated"

The idea of that task was to show logic of dependency in Vue.

Solution

<script> // a class representing a dependency // exposing it on window is necessary for testing window.Dep = class Dep { constructor () { this.subscribers = new Set() } depend () { if (activeUpdate) { // register the current active update as a subscriber this.subscribers.add(activeUpdate) } } notify () { // run all subscriber functions this.subscribers.forEach(subscriber => subscriber()) } } let activeUpdate function autorun (update) { function wrappedUpdate () { activeUpdate = wrappedUpdate update() activeUpdate = null } wrappedUpdate() } </script>

I can't get why do we use activeUpdate and wrappedUpdate in the code. Evan explained that

We're registering wrappedUpdate as activeUpdate, so that when our dependency changes and update function is called again we're in fact calling wrappedUpdate again. We need to make asure that our little dependecy trick is still working on future iterations, and it keeps collecting all dependencies. This is important, cause in some cases our update function may contain conditionals (if true - this dependency, if false - the other). Our dependency collecting system should dynamically rebalance and always keep dependencies up to date

I'm so dumb. Can anyone explain how does it work?

Categories: Software

Rendering particular component in v-for

Thu, 2017-09-14 12:25

I want to render particular component in v-for based on the category present in the array.

Categories: Software

Detect changes to localstorage with Vue and Apollo

Thu, 2017-09-14 12:08

I have a Vue app that uses Apollo to make GraphQL queries and mutations. The Apollo client is set up like so:

import ApolloClient, { createNetworkInterface } from 'apollo-client'; const networkInterface = createNetworkInterface({ uri: '/graphql' }); networkInterface.use([{ applyMiddleware(req, next) { if (!req.options.headers) { req.options.headers = {}; // Create the header object if needed. } req.options.headers['authorization'] = localStorage.getItem('token') ? localStorage.getItem('token') : null; next(); } }]); const client = new ApolloClient({ networkInterface, });

When i log into my API and get the access token I have to refresh the page for the Apollo client to recognize that a token now exists in localStorage. Why doesn't apollo detect the token in localStorage?

Categories: Software

Tried to connect to elasticsearch with axios

Thu, 2017-09-14 11:49

I am new to axios, I'm trying to connect my elasticsearch cloud with axios, I got : error 401 unauthorized.

Here's my code in my vue.js:

axios.get('https://username:password@url:9243/elastictest/apps/_search?pretty',{ params:{ source: JSON.stringify(query), source_content_type: 'application/json' , }, }).then(response =>this.skills =response.data.hits.hits);

I am not sure where I have to put my username and password ?

If you have any ideas or solutions ?

Thanks for your help !

Categories: Software

Vuejs cant refer array

Thu, 2017-09-14 11:44

I can not reference an array in vue js.

console.log(this.ref_number_response[0]);

this show me undefined, and I'm wondering why...

data(){ return{ ref_number_response: [], } }, methods:{ check_ref_number: function () { // axios request axios.get('/is_referenceNumber_free/'+this.ref_number) .then(response => this.ref_number_response.push({ info: response.data })); console.log(this.ref_number_response[0]); Event.$emit('reference_added', this.ref_number_response); }, } <div class="form-group"> <label for="" class="col-sm-2 control-label">Ref Number</label> <div class="col-sm-10"> <input v-model="ref_number" type="text" name="ref_number" class="form-control" id="" placeholder="Referent number" @blur="check_ref_number" required> </div> </div>

This is the response that i get and I do not want to iterrate several times using v-for to get actual diagnosis.

[ { "info": [ { "diagnosis": "St. post. trauma testis sin. Obs Ruptura testis sin." }, { "diagnosis": "diagnosi2" } ] } ]

Categories: Software

Why need default after require() method in Vue?

Thu, 2017-09-14 11:42

There is 2 projects generated by vue-cli.

one of it I could add component like this code below:

Vue.component('HeaderBar',require("./components/common/HeaderBar.vue"));

But another one I can't do this , I must code like this:

Vue.component('HeaderBar',require("./components/common/HeaderBar.vue").default); if not, I will get this error message:

Failed to mount component: template or render function not defined

Is someone could tell me Why like this ?

Thank you for help .

Categories: Software

async await with vuex + feathers

Thu, 2017-09-14 11:41

Please check below my code. I'm trying to implement Async Await into vuex. Everything is working but I want to call another action after this one so I am trying with async await But it's not working. In console console.log("after all this" +res) res variable showing undefined.

action.js

import { createUpload } from '../api/index' export default { fetchImageUrl: async({ commit }, reader) => { let res = await createUpload({ commit }, reader); console.log("after all this" +res) } }

api/index.js

import { feathersClient } from './apiClient' const uploadService = feathersClient.service('uploads'); export const createUpload = ({commit}, reader) => { uploadService .create({uri: reader.result}) .then(function(response){ commit('setImageUrl', { url: response.imageurl }) return true; }); }

mutations.js

export default { setImageUrl: (state,{ url } ) => { state.imageUrl = url } }

LeftPanel.vue

const reader = new FileReader(); export default { name: 'left-panel', data () { return { open: true } }, methods: { uploadFile: function (event) { let store = this.$store; let file = event.target.files[0]; reader.readAsDataURL(file); reader.onload = function(event) { return store.dispatch('fetchImageUrl',reader) }; } }, components: { 'add-text': AddText }, }
Categories: Software

Passing image uri as props in Vue (nuxt)

Thu, 2017-09-14 11:37

I' m trying to pass an image uri to the component as props like this:

<a-blog-article :img='posts[0].imageUrl'></a-blog-article>

This is how I use it in the component:

<template> <div> <img :src="img"> </div> </template> <script> export default { name: 'blogArticle', props: { img: { type: String } } } </script>

But the image is not found. Also, I noticed that if I use in the component the link itself like this:

<img src="../../assets/img/blog-article-1.jpg">

it shows the image (so I assume the passed link is correct) but transforms the html code to something like this:

<img src="/_nuxt/img/blog-article-1.d14a49d.jpg">

So what is the correct way to get the right uri?

Categories: Software

MapBox (mapbox-gl-vue) renders the map on only 50% of the width of the container

Thu, 2017-09-14 11:20

I am trying MapBox with Vue 2 and I cannot make the map take the full width of the container. It only renders on 50% of the width of the container.

I have included the files in the head of my index.html as follows:

<script src='https://api.mapbox.com/mapbox-gl-js/v0.40.0/mapbox-gl.js'></script> <link href='https://api.mapbox.com/mapbox-gl-js/v0.40.0/mapbox-gl.css' rel='stylesheet' />

I want the map in a component (Map.vue, I am using vue-router), so here is the code in Map.vue:

Script:

import Mapbox from 'mapbox-gl-vue'; export default { components: { 'mapbox': Mapbox } }

Template:

<mapbox access-token="pk.eyJ1Ijoic3BlZW5pY3Q....." :map-options="{ style: 'mapbox://styles/mapbox/streets-v9', center: [-96, 37.8], zoom: 3 }" :geolocate-control="{ show: true, position: 'top-left' }" :scale-control="{ show: true, position: 'top-left' }" :fullscreen-control="{ show: true, position: 'top-left' }">> </mapbox>

Style:

#map { width: 100%; height: 600px; position: absolute; margin:0; z-index:1; }

I have tried everything I know in the CSS id but it only renders the map in the right half of the width of the container, in the left one only the logo and the controls are displayed while the rest of the area is empty.

Screenshot

Categories: Software

How can I combine Vue.js with Flask?

Thu, 2017-09-14 10:28

I want to use Vue.js and Flask together: Vue.js for a dynamic front-end, and Flask for the back-end. How can I do that?

Categories: Software

How to make observable from multiple event in Rxjs?

Thu, 2017-09-14 09:42

How are you. I am newbie of Rxjs. I am not sure how to merge observable from different event. I integrated Rxjs with Vue.js

export default { name: 'useraside', data: function () { return { searchKey: '', isPublic: true } }, components: { User }, subscriptions () { return { // this is the example in RxJS's readme. raps: this.$watchAsObservable('searchKey') .pluck('newValue') // .filter(text => text.length > 1) .debounceTime(500) .distinctUntilChanged() .switchMap(terms => fetchRaps(terms, this.userdata._id, this.isPublic)) .map(formatResult) } } }

Now event comes from searchKey changes, now I would like to subscribe same observable when isPublic value change. So I would like to get raps whenever searchKey changes or isPublic changes. Thanks.

Categories: Software

How can I reset dropdown data if modal closed on vue component?

Thu, 2017-09-14 09:29

My case like this

I have two component, parent and child component

My parent component like this :

<template> ... <div class="row"> ... <location-select level="continentList" type="1"/> ... <location-select level="countryList" type="2"/> ... <location-select level="cityList" type="3"/> ... </div> </template> <script> ... export default{ ... } </script>

The parent component is a modal bootstrap

My child component like this :

<template> <select class="form-control" v-model="selected" @change="changeLocation"> <option value="0" disabled>Select</option> <template v-for="option in options"> <option v-bind:value="option.id" >{{ option.name }}</option> </template> </select> </template> <script> ... export default{ props: ['level','type'], data() { return { selected: '' };}, computed:{ ...mapGetters([ 'getContinentList', 'getCountryList','getCityList' ]), options(){ const n = ['getContinentList', 'getCountryList','getCityList'] return this[n[this.type-1]] } }, methods:{ ...mapActions([ 'getLocationList' ]), changeLocation(event){ if(this.type==1){ this.getLocationList([{type:2},{level:'countryList'}]) this.getLocationList([{type:3},{level:'cityList'}]) }else if(this.type==2){ this.getLocationList([{type:3},{level:'cityList'}]) } } }, created() { if(this.type==1) this.getLocationList([{type:1},{level:'continentList'}]) if(this.type==2 && this.selected!='') this.getLocationList([{type:2},{level:'countryList'}]) if(this.type==3 && this.selected!='') this.getLocationList([{type:3},{level:'cityList'}]) }, mounted() { $(this.$parent.$refs.modal).on('hidden.bs.modal', (e) => { Object.assign(this.$data, this.$options.data()) }) }, }; </script>

If the modal show, I select continent, country and city. Then I close the modal

After that I show the modal again. Then I select country and city first, the data is still exist

I want to reset the data. So if I open modal again, before I choose continent, country and city data is not showing

I try :

Object.assign(this.$data, this.$options.data())

and this :

Object.assign(this.$data,this.$options.data.call(this))

and this too :

this.$forceUpdate()

when modal hidden

But, it does not work

Seems it must update data computed:{...}. But I'm still confused to do it

How can I solve this problem?

Categories: Software

Vue.js can't find script tag

Thu, 2017-09-14 09:17

I'm developing an application for restaurant booking. I'm using Vue.js, Monaca and OnsenUI to develop the application. I need to get the restaurant and user location using google map. But, it doesn't show the map. After debugging for several hours found out that, home page can't find the script for google map API. I have <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDX3SEHwFUY-k_Jp7YMp0-uTvo7up-paXM"></script> in my index.html but when I inspect the home page it doesn't show this script but shows all other tags. Why does this happen ? How to get this work ?

index.html

<!DOCTYPE html> <html> <head> <!-- This file is the template for "www/index.html". Modify it to fit your needs --> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <meta http-equiv="Content-Security-Policy" content="default-src * data:; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'"> <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDX3SEHwFUY-k_Jp7YMp0-uTvo7up-paXM"></script> <!-- The following EJS lines include the necessary CSS and JS from Monaca (cordova.js/ loader.js) in production mode --> <link href="main.css" rel="stylesheet"> </head> <body> <div id="app"></div> <map></map> <script type="text/javascript" src="bundle.js"></script> </body> </html>

main.js

import 'onsenui'; import Vue from 'vue'; import VueOnsen from 'vue-onsenui'; // Onsen UI Styling and Icons require('onsenui/css-components-src/src/onsen-css-components.css'); require('onsenui/css/onsenui.css'); import App from './App.vue'; Vue.use(VueOnsen); new Vue({ el: '#app', template: '<app></app>', components: { App } });

Home.vue

<template> <v-ons-page> <p style="text-align: center"> Welcome home. </p> <div id="map"></div> </v-ons-page> </template> <script> export default { data() { return { } }, mounted: function() { this.initMap(); }, methods: { initMap: function() { var map; map = new google.maps.Map(document.getElementById('map'), { center: {lat: 83.9207, lng: 35.9565}, scrollwheel: false, zoom: 14 }) } } } </script> <style> #map {height:300px;width:500px;} </style>

Home page is showing Welcome Home only, nothing else.

Categories: Software

How to convert object's attributes in kebab-case to camelCase [duplicate]

Thu, 2017-09-14 09:05

This question already has an answer here:

I'm receiving a json formatted in kebab-case, like so :

{name: "田中 太郎", profile-image: "", visit-frequency: "10"}

I have multiple objects that I want to display in my template, so I'm using a v-for. But I can't figure out how to display profile-image or visit-frequency, as I obviously can not do :

<li class="cell" v-for="item in members"> <img :src="item.attributes.profile-image" :alt="item.attributes.name"> </li>

I'm thinking about a loop on my list of objects and rename those attributes, but I feel like there something better than that.

Categories: Software

Import style file doesn’t scoped?

Thu, 2017-09-14 08:54

when I try to import CSS file like this, the CSS doesn't scoped.

must write style in style tag that can be work ???

I use the vue-cli to try this

<style scoped> @import "hell.css"; </style>
Categories: Software

How can I reload a vue component?

Thu, 2017-09-14 07:37

I know the solution is update the prop data like this :

this.selectedContinent = ""

But I want to use another solution

After I read some reference, the solution is :

this.$forceUpdate()

I try it, but it does not work

Demo and full code like this :

https://jsfiddle.net/Lgxrcc5p/13/

You can click button test to try it

I need a solution other than update the property data

Categories: Software

Bulma's navbar-buger doesnt connect to menu items in Vue.js 2

Thu, 2017-09-14 07:30

I am trying to implement a navbar for my application whose front end is built using Vue 2.0 and Bulma . It works well on desktops and but on smaller screens its showing the burger icon but it is not showing any elements. Its just present.

<template> <div class="container is-fluid"> <div> <nav class="navbar is-dark"> <div class="navbar-brand"> <a class="navbar-item" href="#"> <img alt="K R O N O S" height="100px"> </a> <div class="button navbar-burger" data-target="navMenu"> <span></span> <span></span> <span></span> </div> </div> <div class="navbar-menu" id="navMenu"> <div class="navbar-end"> <div class="navbar-item"> <a class="" href="#"> Docs </a> </div> <div class="navbar-item "> <a class="" href="#"> Report </a> </div> <div class="navbar-item"> <a class="">More</a> </div> <div class="navbar-item"> <a class="">Logout</a> </div> </div> </div> </nav> </div> </div> </template> <script> document.addEventListener('DOMContentLoaded', function () { // Get all "navbar-burger" elements var $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0) // Check if there are any navbar burgers if ($navbarBurgers.length > 0) { // Add a click event on each of them $navbarBurgers.forEach(function ($el) { $el.addEventListener('click', function () { // Get the target from the "data-target" attribute var target = $el.dataset.target var $target = document.getElementById(target) // Toggle the class on both the "navbar-burger" and the "navbar-menu" $el.classList.toggle('is-active') $target.classList.toggle('is-active') }) }) } }) export default { name: 'Navbar', data () { return { msg: '' } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> div{ border: 0px solid black; } </style>

As you can see I have tried implementing the example code in on which was present here but with no use. Shouldnt Bulma give me responsive navbar out of the box. All the examples and solutions I have found are for the older "nav" class not the newer "navbar". Help would be much appreciated.

Categories: Software

Can we use selenium webdriver to automate VueJS applications?

Thu, 2017-09-14 07:24

I am trying to build a selenium fraewmork for an application which is based on VueJS.It would be great help if somebody can share their knowledge on this topic as it will me in taking a better decision.

Categories: Software

render custom tag from REST API response

Thu, 2017-09-14 06:48

I have the following component MyComponent.vue:

<template> <div v-html="content"></div> </template> <script> import Vue from 'vue' import CustomComponent from 'CustomComponent.vue' Vue.use(CustomComponent) export default { name: `my-component`, computed: { content() { return this.$store.state.content } } // ... } </script>

Where this.$store.state.content is html-string which I get from REST API. For example:

<custom-component data-count="1"></custom-component><p>some text</p>

custom-component tag is not rendered in may case.

Is it possible to render vue component from html-string which I get from REST API and if I use this string in v-html?

Categories: Software

Using a product tour library with VueJS

Thu, 2017-09-14 05:28

I'm trying to setup a feature intro tutorial for my web app (like intro.js). I'm having trouble with intro.js with nothing happening (no error message or tour messages). I tried setting up the data attributes that intro.js uses and calling the tour start from the mounted function on App.vue, but no luck. I'm looking to see if anyone has experience with with libraries like this combined with VueJS.

Code from App.vue:

mounted: function() { const introJS = require('intro.js') introJS.introJs().start() }

Inside of the same component in it's <template>:

<div class="card card-accent-info" v-if="!isLoading" data-intro="Test step here" data-step="1">

I also have the css loaded in App.vue:

@import "~intro.js/minified/introjs.min.css";

Categories: Software

Pages