Software
How to pass data from Vue js method scope to external JS file?
This my component code of vue js
<template> <div class="grapha"> <div id="chart2"></div> </div> </template> <script> // var apiURL = 'https://jsonplaceholder.typicode.com/users'; var apiURL = 'http://localhost:3000/db'; export default { name: 'grapha', data () { return { users:[] } }, methods: { fetchData: function () { var self = this; $.get( apiURL, function( data ) { self.users = data; }); } }, created: function (){ this.fetchData(); } } </script>
Here is my d3 combo chart code , here is a variable named Data takes values and shows it on graph.
Now, I want to get data from self.users (vue js component) to pass it on data variable ( external function ). Could you suggest me what would be the possible way to do that ?
function getTextWidth(text, fontSize, fontName) { c = document.createElement("canvas"); ctx = c.getContext("2d"); ctx.font = fontSize + ' ' + fontName; return ctx.measureText(text).width; } function DataSegregator(array, on) { var SegData; OrdinalPositionHolder = { valueOf: function () { thisObject = this; keys = Object.keys(thisObject); keys.splice(keys.indexOf("valueOf"), 1); keys.splice(keys.indexOf("keys"), 1); return keys.length == 0 ? -1 : d3.max(keys, function (d) { return thisObject[d] }) } , keys: function () { keys = Object.keys(thisObject); keys.splice(keys.indexOf("valueOf"), 1); keys.splice(keys.indexOf("keys"), 1); return keys; } } array[0].map(function (d) { return d[on] }).forEach(function (b) { value = OrdinalPositionHolder.valueOf(); OrdinalPositionHolder[b] = OrdinalPositionHolder > -1 ? ++value : 0; }) SegData = OrdinalPositionHolder.keys().map(function () { return []; }); array.forEach(function (d) { d.forEach(function (b) { SegData[OrdinalPositionHolder[b[on]]].push(b); }) }); return SegData; } Data = self.users.comboChart; var margin = { top: 20, right: 30, bottom: 60, left: 40 }, width = 800 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var textWidthHolder = 0; /// Adding Date in LineCategory Data.forEach(function (d) { d.LineCategory.forEach(function (b) { b.Date = d.Date; }) }); var Categories = new Array(); // Extension method declaration // Categories.pro; var Data; var ageNames; var x0 = d3.scale.ordinal() .rangeRoundBands([0, width], .1); var XLine = d3.scale.ordinal() .rangeRoundPoints([0, width], .1); var x1 = d3.scale.ordinal(); var y = d3.scale.linear() .range([height, 0]); var YLine = d3.scale.linear().range([height, 0]) .domain([0, d3.max(Data, function (d) { return d3.max(d.LineCategory, function (b) { return b.Value }) })]); var color = d3.scale.ordinal() .range(["#6aae6a", "#639ce4", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); var line = d3.svg.line().x(function (d) { return x0(d.Date) + x0.rangeBand() / 2; }).y(function (d) { return YLine(d.Value) }); var xAxis = d3.svg.axis() .scale(x0) .orient("bottom"); // var yAxis = d3.svg.axis() // .scale(y) // .orient("left") // .tickFormat(d3.format(".2s")); // var YLeftAxis = d3.svg.axis().scale(YLine).orient("right").tickFormat(d3.format(".2s")); var svg = d3.select("#chart2").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // Bar Data categories Data.forEach(function (d) { d.Categories.forEach(function (b) { if (Categories.findIndex(function (c) { return c.Name===b.Name}) == -1) { b.Type = "bar"; // console.log(JSON.stringify(b)) Categories.push(b) } }) }); // Line Data categories Data.forEach(function (d) { d.LineCategory.forEach(function (b) { if (Categories.findIndex(function (c) { return c.Name === b.Name }) == -1) { b.Type = "line"; // console.log(JSON.stringify(b)) Categories.push(b) } }) }); // Processing Line data lineData = DataSegregator(Data.map(function (d) { return d.LineCategory }), "Name"); // Line Coloring LineColor = d3.scale.ordinal(); LineColor.domain(Categories.filter(function (d) { return d.Type == "line" }).map(function (d) { return d.Name })); LineColor.range(["#333471", "#386a07", "#7f8ed4", "#671919", "#0b172b"]) x0.domain(Data.map(function (d) { return d.Date; })); XLine.domain(Data.map(function (d) { return d.Date; })); x1.domain(Categories.filter(function (d) { return d.Type == "bar" }).map(function (d) { return d.Name})).rangeRoundBands([0, x0.rangeBand()]); y.domain([0, d3.max(Data, function (d) { return d3.max(d.Categories, function (d) { return d.Value; }); })]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); var state = svg.selectAll(".state") .data(Data) .enter().append("g") .attr("class", "state") .attr("transform", function (d) { return "translate(" + x0(d.Date) + ",0)"; }); state.selectAll("rect") .data(function (d) { return d.Categories; }) .enter().append("rect") .attr("width", x1.rangeBand()) .attr("x", function (d) { return x1(d.Name); }) .attr("y", function (d) { return y(d.Value); }) //.attr("height", function (d) { return height - y(d.Value); }) .style("fill", function (d) { return color(d.Name); }) .transition().delay(500).attrTween("height", function (d) { var i = d3.interpolate(0, height - y(d.Value)); return function (t) { return i(t); } }); // drawaing lines svg.selectAll(".lines").data(lineData).enter().append("g").attr("class", "line") .each(function (d) { Name=d[0].Name d3.select(this).append("path").attr("d", function (b) { return line(b) }).style({ "stroke-width": "3px", "fill": "none" }).style("stroke", LineColor(Name)).transition().duration(1500); }) // Legends var LegendHolder = svg.append("g").attr("class", "legendHolder"); var legend = LegendHolder.selectAll(".legend") .data(Categories.map(function (d) { return {"Name":d.Name,"Type":d.Type}})) .enter().append("g") .attr("class", "legend") .attr("transform", function (d, i) { return "translate(0," +( height+ margin.bottom/2 )+ ")"; }) .each(function (d,i) { // Legend Symbols d3.select(this).append("rect") .attr("width", function () { return 18 }) .attr("x", function (b) { left = (i+1) * 15 + i * 18 + i * 5 + textWidthHolder; return left; }) .attr("y", function (b) { return b.Type == 'bar'?0:7}) .attr("height", function (b) { return b.Type== 'bar'? 18:5 }) .style("fill", function (b) { return b.Type == 'bar' ? color(d.Name) : LineColor(d.Name) }); // Legend Text d3.select(this).append("text") .attr("x", function (b) { left = (i+1) * 15 + (i+1) * 18 + (i + 1) * 5 + textWidthHolder; return left; }) .attr("y", 9) .attr("dy", ".35em") .style("text-anchor", "start") .text(d.Name); textWidthHolder += getTextWidth(d.Name, "10px", "calibri"); }); // Legend Placing (center) d3.select(".legendHolder").attr("transform", function (d) { thisWidth = d3.select(this).node().getBBox().width; return "translate(" + ((width) / 2 - thisWidth / 2) + ",0)"; }) // round the rectangle corners svg.selectAll('rect').attr('rx', 5).attr('ry', 5);
How to make observable with Null value in Rxjs
How are you I am newbie of Rxjs. I implemented Rxjs with Vue.js
export default { name: 'useraside', computed: { ...mapState({ userdata: state => state.app.selectedUser }) }, subscriptions () { return { // this is the example in RxJS's readme. raps: this.$watchAsObservable(this.userdata) .pluck('newValue') .distinctUntilChanged() .switchMap(data => () => { if (data) { fetchRaps(data._id) } }) .map(formatResult) } } }Here, User data is from store of vuex. And it is null at first time. So I got error such as
Error in created hook: "TypeError: Cannot read property 'toString' of null"so How can I mange this?
Vue - Reactive media .readyState
Using Vue.js, I would like to use the readyState property of an audio dom element as a reactive property.
I have the audio element in a component and accessing it with this.$refs.audioPlayer
I have tried setting a computed property to return the property:
audioLoaded(){ if(this.$refs.audioPlayer){ return this.$refs.audioPlayer.readyState; } return false; }This just returns the initial state (0), when the media is loaded, this should change to 4.
Is there any way to make this a reactive property?
Can a vue component know if a listener is listening?
Say I have a modal dialogue as a Vue component. Sometimes I want OK and Cancel. Sometimes, I just want OK. The cleanest way I can think to do this would be for my component to only display Cancel when it's caller is listening for cancel events. Can this be done?
markup
<div id="vue-root"> <confirm-modal v-on:ok="handleOk"></confirm-modal> <confirm-modal v-on:ok="handleOk" v-on:cancel="handleCancel"></confirm-modal> </div>code
Vue.component('confirm-modal',{ template : ` <div class="confirm-modal"> Are you sure<br> <button v-on:click="$emit('ok',{})">OK</button> <button v-if="'HOW DO I TEST IF CANCEL WILL BE CAPTURED???'" v-on:click="$emit('cancel',{})">Cancel</button </div> `, }) vm = new Vue({ el : '#vue-root', methods : { handleOk : function(){ alert('OK already'); }, handleCancel : function(){ } } })Public Event: The Fate of Net Neutrality in the U.S.
Net neutrality is under siege.
Despite protests from millions of Americans, FCC Chairman Ajit Pai is moving forward with plans to dismantle hard-won open internet protections.
“Abandoning these core protections will hurt consumers and small businesses alike,” Mozilla’s Heather West penned in an open letter to Pai earlier this week, during Pai’s visit to San Francisco.
The FCC may vote to gut net neutrality as early as October. What does this mean for the future of the internet?
Join Mozilla and the nation’s leading net neutrality experts at a free, public event on September 18 to discuss just this. We will gather at the Internet Archive to discuss why net neutrality matters to a healthy internet — and what can be done to protect it.
RSVP: The Battle to Save Net Neutrality
<WHAT>The Battle to Save Net Neutrality, a reception and discussion in downtown San Francisco. Register for free tickets
<WHO>Mozilla Tech Policy Fellow and former FCC Counselor Gigi Sohn will moderate a conversation with the nation’s leading experts on net neutrality, including Mozilla’s Chief Legal and Business Officer, Denelle Dixon, and:
Tom Wheeler, Former FCC Chairman who served under President Obama and was architect of the 2015 net neutrality rules
Representative Ro Khanna, (D-California), who represents California’s 17th congressional district in the heart of Silicon Valley
Amy Aniobi, Supervising Producer of HBO’s “Insecure”
Luisa Leschin, Co-Executive Producer/Head Writer of Amazon’s “Just Add Magic”
Malkia Cyril, Executive Director of the Center for Media Justice
and Dane Jasper, CEO and Co-Founder of Sonic.
<WHEN>Monday, September 18, 2017 from 6 p.m. to 9 p.m. PT
<WHERE>The Internet Archive, 300 Funston Avenue San Francisco, CA 94118
RSVP: The Battle to Save Net Neutrality
The post Public Event: The Fate of Net Neutrality in the U.S. appeared first on The Mozilla Blog.
VueJs Tree recursive elements emits to parent
How do you emit event inside recursive child components vuejs
Taking the tree example from vue site https://vuejs.org/v2/examples/tree-view.html
How would you transmit on click to the parent each clicked elements id?
can't import vue component from npm package
Good day,
I have recently created an npm package for a navigation-bar which I want to import into my main codebase. I am using vue @components and I can't quite find out how to use the imported component. If anyone knows how to get the npm packaged component into the dom, your help would be greatly appreciated.
Below is a simplified example of what I have tried:
npm package import Vue from 'vue'; import Component from 'vue-class-component'; import '../navigation-bar.styles.less'; @Component({template: require('../navigation-bar.html')}}) export class NavigationBar extends Vue { constructor() { super(); } } Vue.component('navigation-bar', NavigationBar); main.ts import { NavigationBar } from '@international-client/navigation-bar'; Vue.component('navigation-bar', NavigationBar); index.html <html> <head> <title>Game</title> </head> <navigation-bar></navigation-bar> <body class="game-view"> </body> </html>Vuejs v-for multidimensional array json_object
I try to loop through a multidimensional json_object using the vueJS v-for function.
But i get the following error:
[Vue warn]: Error in render function: "TypeError: Cannot read property 'id' of null"
My code looks like this:
<tr v-for="timeblock in responseAPI"> <td> {{timeblock.time}} </td> <td v-for="value in timeblock.appointment"> {{value.id}} </td> <td> {{timeblock.break}} </td> <td> {{timeblock.scheduled}} </td> <td> {{timeblock.text}} </td> </tr>And my json_object like this:
[ { "time": "09:00", "break": null, "scheduled": "Stoel 1", "appointment": { "id": 1, "patient_id": 1, "chair_id": 1, "date": "2017-05-10", "time": "09:00:00", "duration": 30, "treatment_type": "Controle", "created_at": null, "updated_at": null }, "text": null }, { "time": "09:30", "break": null, "scheduled": "Stoel 1", "appointment": { "id": 2, "patient_id": 2, "chair_id": 1, "date": "2017-05-10", "time": "09:30:00", "duration": 30, "treatment_type": "Controle ", "created_at": null, "updated_at": null }, "text": null } ]Vue.js can't access this (or method return) from component method
I have a component which passes data to a method, but I need to further change the data, so I am trying (without sucess) to pass it off to a function, but it is not working, whether I place the function inside the method or outside. The problem seems to be that this is unreachable in either case, resulting in undefined warnings.
What is strange is that my second method (photoConvert) IS being called (as my console.log output proves), but the data never gets returned to the calling method (onChange). I have tried setting a value in data, tried simply returning the value, nothing works, it always shows as undefined
Here are my methods:
methods: { photoConvert (file) { var f = file var fr = new FileReader() fr.readAsDataURL(f) fr.onload = function () { var tempImage = new Image() tempImage.src = fr.result var height = tempImage.height var width = tempImage.width if (height > 150) { width = width / (height / 150) height = 150 } if (width > 150) { height = height / (width / 150) width = 150 } var c = document.createElement('canvas') c.width = width c.height = height var ctx = c.getContext('2d') ctx.drawImage(tempImage, 0, 0, width, height) var b64str = c.toDataURL('image/jpeg') console.log(b64str) //this outputs correctly, so we know it was called this.b64str = b64str //tried setting data element to no effect return b64str //never gets to method calling this function } }, onChange () { if (this.$refs.pictureInput.file) { console.log('Picture loaded.') // we got it var final64 = this.photoConvert(this.$refs.pictureInput.file) console.log(final64) // fails, says undefined } else { console.log('FileReader API not supported') } } },Vue.js - How to get last child ref in v-for children components
I want to play latest audio after page is loaded:
<player ref="player" v-for="item in data"><player>
how can I do something like this:
vm.$refs.player.last().play();
Vuejs append data-attribute conditionally
I try to add conditionally a data attribute value to my vue list on loop and I try the following
<ul data-parent="{{model.parent_id !== null ? model.parent_id : 0}}"></ul>but in this case the list do not renders anymore, if dump out outside html tag {{model.parent_id !== null ? model.parent_id : 0}} than I see the correct output
Dependency Tracking function in JS
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?
Rendering particular component in v-for
I want to render particular component in v-for based on the category present in the array.
Detect changes to localstorage with Vue and Apollo
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?
Tried to connect to elasticsearch with axios
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 !
Vuejs cant refer array
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" } ] } ]
Why need default after require() method in Vue?
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 .
async await with vuex + feathers
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 }, }Passing image uri as props in Vue (nuxt)
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?
MapBox (mapbox-gl-vue) renders the map on only 50% of the width of the container
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.