Access external js files on vue instance - javascript

I am developing a simple app, where i set a list of consts that i want to use in my development. so i created a file like this:
consts.js
export default {
MAX_HEALTH: 100,
MAX_HEALTH_PERCENTAGE: '100%',
ATTACK_FLAG: 1,
HEALTH_FLAG: -1,
PERCENTAGE: '%',
ATTACK_MIN_RANGE: 1,
ATTACK_YOU_MAX_RANGE: 10,
ATTACK_MONSTER_MAX_RANGE: 7,
SPECIAL_ATTACK_MIN_RANGE: 5,
SPECIAL_ATTACK_YOU_MAX_RANGE:12,
HEAL_MIN_RANGE: 1,
HEAL_MAX_RANGE: 10
}
and i want to access the consts in a separate file on the vue instance:
window.onload = function () {
new Vue({
el: '#appMonster',
data: {
startClicked: false,
monsterLife: {
width: '100%',
life: 100
},
youLife: {
width: '100%',
life: 100
}
},
methods: {
...
for example inside methods, how can i do it?
I already tried to import the file at the top before and after onload, but i always get this error: unexpected identifier, any way to solve this?
I am not using webpack, I am just working with the vue instance accessing the vue script cdn with basic script import.
Thank you

I am not using webpack, I am just working with the vue instance accessing the vue script cdn with basic script import.
If that's the case, don't use import/export. Just:
consts.js:
const constants = {
MAX_HEALTH: 100,
MAX_HEALTH_PERCENTAGE: '100%',
ATTACK_FLAG: 1,
HEALTH_FLAG: -1,
PERCENTAGE: '%',
ATTACK_MIN_RANGE: 1,
ATTACK_YOU_MAX_RANGE: 10,
ATTACK_MONSTER_MAX_RANGE: 7,
SPECIAL_ATTACK_MIN_RANGE: 5,
SPECIAL_ATTACK_YOU_MAX_RANGE:12,
HEAL_MIN_RANGE: 1,
HEAL_MAX_RANGE: 10
}
Other file, provided you imported <script src="consts.js"></script> before, simply do:
// somewhere before: <script src="consts.js"></script>
<script>
window.onload = function () {
new Vue({
el: '#appMonster',
data: {
startClicked: false,
monsterLife: {
width: '100%',
life: constants.MAX_HEALTH // <==== use constants.PROPNAME
},
youLife: {
width: '100%',
life: 100
}
},
methods: {
See plunker demo here.

Related

How to use sigma.js with svelte

I've been trying load sigma.js with Svelte / Sveltekit but there seems to be no component integration nor any guidance on how to do this. I tried loading it as client-only code in Sveltekit unsuccessfully but I have no idea if this a legit approach. Is there any working example of a simple graph in Sigma.js running with Sveltekit?
Example for parsing a gexf file:
<script lang="ts">
import Sigma from 'sigma';
import Graph from 'graphology';
import { onMount } from 'svelte';
let container: HTMLElement;
onMount(async () => {
const res = await fetch('/arctic.gexf');
const gexf = await res.text();
const { parse } = await import('graphology-gexf/browser');
const graph = parse(Graph, gexf);
const renderer = new Sigma(graph, container, {
minCameraRatio: 0.1,
maxCameraRatio: 10,
});
})
</script>
<div bind:this={container} class="container" />
<style>
.container {
width: 800px;
height: 600px;
}
</style>
Required packages:
sigma
graphology
graphology-gexf (for reading .gexf files)
graphology-gexf has two modes, one for Node, one for the Browser. To prevent errors in SSR, the browser part can be dynamically imported.
In Svelte you get access to the DOM elements via bind:this instead of querying the DOM, most other things are not that different. Elements bound this way are available in onMount.
arctic.gexf is placed in the static directory. Code is adapted from this example (without all the additional functionality).
I created a simple svelte-sigma app like this:
npm init vite svelte-sigma -- --template svelte
cd my-app
npm install
npm run dev
after I installed sigma.js:
npm install graphology sigma
Now I changed App.svelte like this:
App.svelte
<script>
import Sigma from 'sigma';
import Graph from 'graphology';
import { onMount } from 'svelte';
onMount(() => {
const container1 = document.getElementById("sigma-container");
const graph = new Graph();
graph.addNode("John", { x: 0, y: 10, size: 15, label: "John", color: "blue" });
graph.addNode("Mary", { x: 10, y: 0, size: 10, label: "Mary", color: "green" });
graph.addNode("Thomas", { x: 7, y: 9, size: 20, label: "Thomas", color: "red" });
graph.addNode("Hannah", { x: -7, y: -6, size: 25, label: "Hannah", color: "teal" });
graph.addEdge("John", "Mary");
graph.addEdge("John", "Thomas");
graph.addEdge("John", "Hannah");
graph.addEdge("Hannah", "Thomas");
graph.addEdge("Hannah", "Mary");
const renderer = new Sigma(graph, container1);
});
</script>
<h1> Sigma graph exemple</h1>
<div id="sigma-container" />
<style>
#sigma-container {
width: 550px;
height: 450px;
}
</style>
and I have this render on my localhost:
You can see this exemple

Convert JS script into React component

I have been trying to use this simple javascript script (https://seatchart.js.org/ or https://github.com/omarmahili/seatchart.js) in my react application. In a html project, one would only add the script and run it, but I struggle with the integration to the React framework. Any approach suggestion would be greatly appreciated.
I have tried some patch work without much success i.e.
Calling the JS function from the script in my react component, but "let sc = new Seatchart(options);", provokes a "'Seatchart' is not defined" error.
Adding "window" in "let sc = new window.Seatchart(options); " results in "Cannot read property 'appendChild' of null" error at "document.getElementById(options.map.id).appendChild(mapContainer)". (may be because the compiler cannot find "document" which is much realted to html and and not much related to React.)
Using UseRef() compiled, but returned a blank screen...
My failling code below omits the entire 1800 lines script which I copied pasted above the React function for "Seatchart()" to be accessed. The script is here
export default function Tickets () {
let options = {
map: {
id: 'map-container',
rows: 9,
columns: 9,
// e.g. Reserved Seat [Row: 1, Col: 2] = 7 * 1 + 2 = 9
reserved: {
seats: [1, 2, 3, 5, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21],
},
disabled: {
seats: [0, 8],
rows: [4],
columns: [4]
}
},
types: [
{ type: "regular", backgroundColor: "#006c80", price: 10, selected: [23, 24] },
{ type: "reduced", backgroundColor: "#287233", price: 7.5, selected: [25, 26] }
],
cart: {
id: 'cart-container',
width: 280,
height: 250,
currency: '£',
},
legend: {
id: 'legend-container',
},
assets: {
path: "../../public",
}
};
let sc = new Seatchart(options);
return (
<div>
<div id="map-container">
</div>
<div id="legend-container">
</div>
<div id="shoppingCart-container">
</div>
</div>
);
}
};
Conceptually, how would I integrate a JS script to my React component?
UPDATE:
In public/index.html:
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<script type="text/javascript" src="../src/containers/SeatChart.js" ></script>
<div id="root"></div>
In SeatChart:
// SeatChart.js script and Option arg. above, but too long to post...
let sc = new Seatchart(options);
localStorage.setItem("scObj", sc);
localStorage.setItem("test", "this is a test");
console.log("You would see this if SeatChart ran successfully);
In Ticket.js
export default function Ticket () {
const sc = localStorage.getItem("scObj");
console.log(sc);
const test = localStorage.getItem("test");
console.log(test)
return (
<div>
<div>Hello from here!</div>
<div id="map-container">
</div>
<div id="legend-container">
</div>
<div id="shoppingCart-container">
</div>
</div>
);
};
Follow below steps:
create a js file in your react application in root, say 'init.js', where you import the required script.
now init.js should have access to let sc = new Seatchart(options)
write your required logic, and return/save/dispatch the result to redux store or local storage. (store.dispatch() can be used.)
2.simply import the aboveenter code here script in your index.html file in your react application.
In your component, read the output from redux/ local-storage as processed by the script function.

Getting "TypeError: "_Ctor" is read-only" when using import for a component in a Vue + .Net core app

I'm a bit of a newbie with Vue (v2) and am trying to integrate it into a .net core mvc application. Essentially, I am planning on only using it on one or two pages but will have a number of nested components.
My problem (I think) is that I'm not using webpack and am just using .js files for the components. To do this, I'm trying to import the components as required. When I got started, I was just using script tags to bring in components as none were nested. However, I'm now finding the need to get the imports working and am having a problem which I can't seem to resolve.
My page looks as such (Simplified):
<div id="app" style="margin-top: 20px;"></div>
<script type="module">
import * as ComponentContainer from '#Href("~/js/components/ComponentContainer.js")';
new Vue({
el: '#app',
data: function () {
return {
bComponents: [
{
type: 'Type A',
sortOrder: 1,
uniqueId: 'ABCDEF'
},
{
type: 'Type B',
sortOrder: 3,
uniqueId: '123456'
},
{
type: 'Type A',
sortOrder: 2,
uniqueId: 'QWERTY'
}
],
editMode: false
}
},
methods: {
componentMethod(selectorId) {
console.log(selectorId);
},
},
computed: {
sortedBComponents: function () {
return this.bComponents.sort((a, b) => a.sortOrder - b.sortOrder);
}
},
components: {
'component-container': ComponentContainer
},
template: `
<div>
<component-container v-for="comp in sortedBComponents"
:key="comp.uniqueId"
:componentData="comp"
:editMode="editMode"
##component-method="componentMethod">
</component-container>
</div>
`
});
</script>
The component (component-container) has the following code:
export { ComponentContainer }
var ComponentContainer = {
props: ['componentData', 'editMode'],
mounted: function() {
},
methods: {
componentSelected() {
this.$emit('component-method', this.componentData.uniqueId);
}
},
components: {
},
template: `
<div :id="componentData.uniqueId + '-contianer'">
{{componentData.type}}, {{componentData.sortOrder}} & {{componentData.uniqueId}}
<a type="button" #click="componentSelected">Test</a>
</div>
`
}
This worked when the component was referenced via the script tag, but since trying to get it to work with the 'import' method, it appears to fail in a way were I can't figure out what's happening.
I get the following error in the conosle:
[Vue warn]: Error in render: "TypeError: "_Ctor" is read-only"
(found in <Root>)
And:
TypeError: "_Ctor" is read-only
I can't seem to figure out what this refers to. I know that the ComponentContainer is being loaded as I can write it to the console but maybe it's not loading in correctly. It works if I bring in the component through a script tag, but not through the import method.
Many thanks in advance for looking at this.
Try this:
import { ComponentContainer } from '/js/components/ComponentContainer.js';

PowerBI Embedded - how to customize menu operation/context and custom layout

I have integrated powerbi-embedded with Angular 9 web app also add code for custom layut but it's not working.
I want to customize operations menu /context and custom layout.
Configuration object -
const config: any = {
type: 'report',
uniqueId: 'report-id',
permissions: this.model.Permissions.All,
embedUrl: 'embed-url',
accessToken: 'access-token',
settings: {
layoutType: this.models.LayoutType.Custom,
customLayout: {
pageSize: {
type: this.models.PageSizeType.Custom,
width: 1600,
height: 1200
},
displayOption: this.models.DisplayOption.ActualSize,
pagesLayout: {
"MyReportSection007" : {
defaultLayout: {
displayState: {
mode: this.models.VisualContainerDisplayMode.Hidden
}
},
visualsLayout: {
"VisualContainer1": {
x: 1,
y: 1,
z: 1,
width: 400,
height: 300,
displayState: {
mode: this.models.VisualContainerDisplayMode.Visible
}
},
"VisualContainer2": {
displayState: {
mode: this.models.VisualContainerDisplayMode.Visible
}
},
}
}
}
}
}
};
Above config. not working. any idea how can i achived customization in menu operation and layout.
I'm following below docs -
https://microsoft.github.io/PowerBI-JavaScript/demo/v2-demo/index.html#
https://github.com/microsoft/PowerBI-JavaScript/wiki/Custom-Layout
Thanks,
Your query is not clear since you have not shared any error message.
Though, code snippet that you shared offers a correct solution but, it might be possible that you are using wrong names for visual containers (i.e. VisualContainer1 or VisualContainer2) or the report page name (i.e. MyReportSection007). Ensure that you are providing correct names.
And if possible, please share the error message as well.

Trouble implementing NavigationView - Sc.View is not observable

When I try to push a view on the view stack of my NavigationView using
MyApp.getPath('mainPage.mainPane.content.nav').push(MyApp.MyView);
It gives me this:
Uncaught TypeError: Object function (props) {
this.__sc_super__ = ret.prototype;
return this._object_init(props);
} has no method 'get'
Obviously, SC.View is not KVO compliant. Then is it a bug in the SproutCore framework? Because they do this in the SC.NavigationView source:
view.get("topToolbar"); // with `view` being the view I passed in as shown above
MyApp.MyView looks like this:
MyApp.MyView = SC.View.extend({
childViews: 'search results'.w(),
search: SC.TextFieldView.design({
layout: { centerX: 0, top: 40, width: 400, height: 30 },
hint: "Search"
}),
results: SC.TemplateView.design({
templateName: 'results'
}),
topToolbar: SC.NavigationBarView.design({
childViews: ['title'],
layout: { height: 44 },
title: SC.LabelView.design({
controlSize: SC.LARGE_CONTROL_SIZE,
layout: { width: 100, height: 24, centerX: 0, centerY: 0 },
value: 'Title'
})
})
});
But I think the SproutCore developers are way smarter and more experienced than I am, so it's probably something I did.
Why doesn't my SC.View subclass have a get() method?
It looks like your view hasn't been created yet, so it's still a class rather than an instance. Classes don't have .get, only instances. If you're getting fancy (definitely encouraged :) ) with passing views around, rather than simply letting the childView hierarchy handle them, you have to create them as well. Try passing in MyApp.MyView.create() instead.

Categories

Resources