How to pass VueJS data to another script? - javascript

I'm converting an established site over to VueJS but hit a stumbling block on the best way to achieve this.
It's using D3-Funnel (https://github.com/jakezatecky/d3-funnel) to draw a funnel chart but how do I pass VueJS data variables to the charts constructor?
<script>
const data = [
{ label: 'Step 1', value: this.step1 },
{ label: 'Step 2', value: this.step2 },
.......
];
const options = {
block: {
dynamicHeight: true,
minHeight: 15,
},
};
const chart = new D3Funnel('#funnel');
chart.draw(data, options);
</script>
So I need to pass vue data variables into the values. My first thought is to move this into it's own function in the VueJS methods object and use the variables there using this.
Is there a better way of achieving this?
---------- Edit -------------
As per comments people wanted to see how I achieved this currently in vue. As already mentioned above I just created a function in the vue methods object and then call it.
methods : {
drawChart(){
const data = [
{ label: 'Step 1', value: 99999 },
{ label: 'Step 2', value: 9999 },
.......
];
const options = {
block: {
dynamicHeight: true,
minHeight: 15,
},
};
const chart = new D3Funnel('#funnel');
chart.draw(data, options);
}
},
mounted(){
this.drawChart();
}
Data is coming from an API and put into the vue data object.
data:{
step1: 0,
step2: 0,
....
},
methods:{
getData(){
axois.post......
response{
this.step1 = response.data.step1
this.step2 = response.data.step2
....
}
}
}

As I understand it you are trying to pass information down to a component and use it. If you are using single file components and webpack you can do something like this which is put together with examples listed on the vue website.
You can also take a look at this guys approach
App.vue
...
<my-d3-component :d3data="d3Data"></my-d3-component>
...
<script>
import d3Component from 'path/to/component'
var app = new Vue({
el: '#app',
data: {
d3Data: {}
},
components: {
'my-d3-component': d3Component
}
})
</script>
d3Component.vue
<template>
d3 html stuff goes here
</template>
<script>
export default {
props: ['d3Data'],
data() {
return {}
},
mounted: {
const options = {
block: {
dynamicHeight: true,
minHeight: 15,
},
};
const chart = new D3Funnel('#funnel');
chart.draw(this.d3Data, options);
}
}
</script>

Related

Inserting Vanilla JS into VueJS framework

With the concept of VueJS is a kind of framework of JS, then it should have no problem inserting the vanilla JS into it. The following is the attempt to insert the pure JS code into vue-cli project(webpack structure).
[Before Start] I tried the example code as the following link(official document)
URL: https://codepen.io/Tobyliao/pen/ZEWNvwE?editable=true%3Dhttps%3A%2F%2Fdocs.bokeh.org%2F
it works.
[Question] As I tried to imlement into Vue project. It fails. picture1 is the directory structure.
I tried to place the src url include into ./public/html's tag as following:
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.2.1.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.2.1.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.2.1.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-api-2.2.1.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-api-2.2.1.min.js"></script>
Create a componet in './src/components/BokehPlot.vue'
inside the code, I insert
<template>
<h1>Measurement Plotting</h1>
</template>
<script src='./main.js'>
export default {
}
</script>
Then finally place all the Bokeh code into './src/component/main.js'. It is the pure JS code I want to import into the structure.
[Result]
I can see the plot in the background, but it kept on showing the error message like picture2.
You have many options here, I went ahead and simply made a mixin to utilize the component lifecycle that Vue provides. source
Here are the relevant parts:
BokehPlot.vue
<template>
<h1>治具量測</h1>
</template>
<script>
import Chart from "#/mixins/Chart";
export default {
mixins: [Chart],
};
</script>
Chart.js
export default {
data() {
return {
plot: null,
xdr: null,
ydr: null
};
},
beforeMount() {
// create some ranges for the plot
this.xdr = new Bokeh.Range1d({ start: -1, end: 100 });
this.ydr = new Bokeh.Range1d({ start: -0.5, end: 20.5 });
// make the plot
this.plot = new Bokeh.Plot({
title: "BokehJS Plot",
x_range: this.xdr,
y_range: this.ydr,
plot_width: 400,
plot_height: 400,
background_fill_color: "#F2F2F7"
});
},
mounted() {
this.loadData();
},
methods: {
loadData() {
// create some data and a ColumnDataSource
let x = Bokeh.LinAlg.linspace(-0.5, 20.5, 10);
let y = x.map(function (v) {
return v * 0.5 + 3.0;
});
let source = new Bokeh.ColumnDataSource({ data: { x: x, y: y } });
// add axes to the plot
let xaxis = new Bokeh.LinearAxis({ axis_line_color: null });
let yaxis = new Bokeh.LinearAxis({ axis_line_color: null });
this.plot.add_layout(xaxis, "below");
this.plot.add_layout(yaxis, "left");
// add grids to the plot
let xgrid = new Bokeh.Grid({ ticker: xaxis.ticker, dimension: 0 });
let ygrid = new Bokeh.Grid({ ticker: yaxis.ticker, dimension: 1 });
this.plot.add_layout(xgrid);
this.plot.add_layout(ygrid);
// add a Line glyph
let line = new Bokeh.Line({
x: { field: "x" },
y: { field: "y" },
line_color: "#666699",
line_width: 2
});
this.plot.add_glyph(line, source);
Bokeh.Plotting.show(this.plot);
}
}
};
Many decisions to still make, but hopefully that will get you pointed down the right path.
See working example:
https://codesandbox.io/s/bokehjs-forked-4w20k?fontsize=14&hidenavigation=1&theme=dark

setInlineProgress is not defined error FrameWork7-vue

I am trying to implement a progress bar based on the docs.
Here I found a few examples and the function is set in the methods object.
I did declare the function, but when I try to use it says that the function is not defined. I cannot even print the console.log inside, so the function is not executed at all.
I will be happy to hear some suggestions. Thanks.
<template id="page-highpth">
<f7-page>
<f7-navbar>
<f7-nav-left title="Form" back-link="" sliding>
<f7-link back-link="Back" ></f7-link>
</f7-nav-left>
<f7-nav-center sliding>High or rising PTH</f7-nav-center>
<f7-nav-right>
<f7-link icon="icon-bars" open-panel="right"></f7-link>
</f7-nav-right>
</f7-navbar>
<f7-block strong>
<p><f7-progressbar :progress="10" id="demo-inline-progressbar"></f7-progressbar></p>
<f7-segmented raised>
<f7-button #click="setInlineProgress(10)">10%</f7-button>
<f7-button #click="setInlineProgress(30)">30%</f7-button>
<f7-button #click="setInlineProgress(50)">50%</f7-button>
<f7-button #click="setInlineProgress(100)">100%</f7-button>
</f7-segmented>
</f7-block>
</f7-page>
</template>
app.js
var app = new Vue({
el: '#app',
methods: {
toHomeScreen(){
this.$f7.getCurrentView().router.back({ pageName: 'home-page', force: true});
this.$f7.closePanel();
},
setInlineProgress(value){
const self = this;
const app = self.$f7;
console.log(value);
app.progressbar.set('#demo-inline-progressbar', value);
}
},
// Init Framework7 by passing parameters here
framework7: {
root: '#app',
/* Uncomment to enable Material theme: */
// material: true,
routes: [
{
path:'/',
name: 'home'
}
,
{
path: '/education/',
component: 'page-education'
},
{
path: '/ckdmbddef/',
component: 'page-mbddef'
},
],
}
});
Ok, after around 6 hours I finnaly reailised that in order to access the function, I need to reference it.
var app = new Vue({...blah});
All I had to do was: app.setInlineProgress() in my code, not setInlineProgress();
Hope this will be useful to someone.

Is there any way to have multiple Vues have a computed listener working on the same value?

Setup:
I have multiple Vue components, and each component has multiple instances in different dialogs in my web app.
For each type of component I have a global state (handrailOptions in the example below) so that each type of component stays in sync across the dialogs.
I'd like for it so that when a component proceeds beyond step 1, I hide the other components in that dialog.
I have achieved this nicely using the computed / watch combo.
However, my problem is that it seems if I try to listen in with computed through more than 1 Vue instance, it hijacks the other listeners.
Problem
Below is a simplified version of what I'm working with, when the app starts up, the console logs 'computed 1' & 'computed 2'. But then when I change handrailOptions.step, only the second fires. ('computed 2' & 'watched 2')
Is there any way to have multiple Vues have a computed listener working on the same value?
handrailOptions = {
step: 1
};
Vue.component( 'handrail-options', {
template: '#module-handrail-options',
data: function() {
return handrailOptions;
},
});
var checkoutDialog = new Vue({
el: '#dialog-checkout',
computed: {
newHandrailStep() {
console.log('computed 1');
return handrailOptions.step;
}
},
watch: {
newHandrailStep( test ) {
console.log('watched 1');
}
}
});
new Vue({
el: '#dialog-estimate-questions',
computed: {
newHandrailStep() {
console.log('computed 2');
return handrailOptions.step;
}
},
watch: {
newHandrailStep( test ) {
console.log('watched 2');
}
}
});
This works as expected. I made handrailOptions responsive by making the data object of a new Vue. Making it the data object of a component, as you did, could also work, but the component would have to be instantiated at least once. It makes more sense to have a single object for your global, anyway.
handrailOptions = {
step: 1
};
// Make it responsive
new Vue({data: handrailOptions});
var checkoutDialog = new Vue({
el: '#dialog-checkout',
computed: {
newHandrailStep() {
console.log('computed 1', handrailOptions.step);
return handrailOptions.step;
}
},
watch: {
newHandrailStep(test) {
console.log('watched 1');
}
}
});
new Vue({
el: '#dialog-estimate-questions',
computed: {
newHandrailStep() {
console.log('computed 2', handrailOptions.step);
return handrailOptions.step;
}
},
watch: {
newHandrailStep(test) {
console.log('watched 2');
}
}
});
setInterval(() => ++handrailOptions.step, 1500);
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="dialog-estimate-questions">
Main step {{newHandrailStep}}
</div>
<div id="dialog-checkout">
CD step {{newHandrailStep}}
</div>

How do I display data through components with Vue.js (using Vueify)?

I'm having trouble getting data to display in my Vue components. I'm using Vueify and I'm trying to load an array of listings from the listings.vue component and I keep getting errors. Also, I don't understand how to pull in the data via the computed method. Any help would be appreciated.
This is the error I'm getting in the console:
[Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions.
[Vue warn]: $mount() should be called only once.
Here is my app.vue
// app.vue
<style>
.red {
color: #f00;
}
</style>
<template>
<div class="container">
<div class="listings" v-component="listings" v-repeat="listing"></div>
</div>
</template>
<script>
module.exports = {
replace: true,
el: '#app',
components: {
'listings': require('./components/listings.vue')
}
}
</script>
Here is my listings.vue component
<style>
.red {
color: #f00;
}
</style>
<template>
<div class="listing">{{title}} <br> {{description}}</div>
</template>
<script>
module.exports = {
data: {
listing: [
{
title: 'Listing title number one',
description: 'Description 1'
},
{
title: 'Listing title number two',
description: 'Description 2'
}
]
},
// computed: {
// get: function () {
// var request = require('superagent');
// request
// .get('/post')
// .end(function (res) {
// // Return this to the data object above
// // return res.title + res.description (for each one)
// });
// }
// }
}
</script>
The first warning means when you are defining a component, the data option should look like this:
module.exports = {
data: function () {
return {
listing: [
{
title: 'Listing title number one',
description: 'Description 1'
},
{
title: 'Listing title number two',
description: 'Description 2'
}
]
}
}
}
Also, don't put ajax requests inside computed properties, since the computed getters gets evaluated every time you access that value.

List and store binding... exact same data

I am using sencha to create a carousel which has multiple card panels. Each panel contains a list component that is attached to its own instance of a store.
All lists store instances call the same API to fetch the data but with different parameters.
Example:
Card 1, Has list 1 attached to Store 1 which calls mywebsite.com/api?node=1
Card 2, Has list 2 attached to Store 2 which calls mywebsite.com/api?node=2
Card 1 shows the right set of nodes retrieved from the API. But once i swipe to see card 2, both list 1 and list 2 show the exact same data although each one should have its own list od data.
Code:
Test.data.NodeStore = Ext.extend(Ext.data.Store, {
constructor : function(config) {
config = Ext.apply({
model: 'Test.models.Node',
autoLoad: false,
pageSize: 20,
proxy: {
type: 'scripttag',
url: Test.API.URL + '?action=getNodes',
extraParams: {
},
reader: {
type: 'json'
}
},
setSource: function(source) {
if(this.getProxy().extraParams.sourceID != source) {
this.getProxy().extraParams.sourceID = source;
}
}
}, config);
Test.data.NodeStore.superclass.constructor.call(this, config);
},
onDestroy : function(config) {
Test.data.NodeStore.superclass.onDestroy.apply(this, arguments);
}
});
Ext.reg('NodeStore', Test.data.NodeStore);
The list view:
Test.views.ListView = Ext.extend(Ext.Panel, {
sourceID: 0,
layout: {
type: 'vbox',
align: 'stretch'
},
items: [
{
xtype: 'list',
itemTpl : new Ext.XTemplate("<div class='node'>{title}</div>"),
store: Ext.create(Test.data.NodeStore, {}),
}
],
setSource: function(source) {
this.sourceID = source;
var store = this.items.get(0).getStore();
store.setSource(source);
store.load();
}
});
The main view which creates list views dynamically
Test.views.Viewer = Ext.extend(Ext.Carousel, {
indicator: false,
layout: 'card',
style: {
padding: '0 20px'
},
items: [
],
loadListView: function(listIndex) {
var currentRecord = Test.stores.ListStore.getAt(listIndex);
var newList = new Test.views.ListView();
newList.setSource(currentRecord.get('ID'));
this.add(newList);
this.doLayout();
},
initComponent: function() {
Test.views.Viewer.superclass.initComponent.apply(this, arguments);
loadListView(1);
loadListView(2);
}
});
This is really wierd... i am just wondering, is sencha assigning the exact same store, model, list component... don't know where to look
In the loadListView function, i had to create an object of store and assign it to the list dynamically rather than modifying existing store.
newList.items.get(0).store = Ext.create(Test.data.NodeStore, {});

Categories