I see that A-Frame is used to build virtual reality experiences with just markup/HTML. How can I use JavaScript alongside the A-Frame markup elements?
A-Frame is a JavaScript/three.js framework, and the HTML is just the outermost declarative layer.
Manipulating the DOM
https://aframe.io/docs/0.2.0/core/entity.html
All elements/objects in A-Frame are entities. We can manipulate these elements using standard DOM methods.
var boxEl = document.querySelector('a-box');
boxEl.setAttribute('width', 5);
boxEl.setAttribute('color', '#FFF');
boxEl.addEventListener('click', function () {
// If we are using the cursor component.
boxEl.setAttribute('color', '#FFF');
});
boxEl.emit('some-event');
boxEl.removeAttribute('color');
boxEl.querySelectorAll('a-sphere');
var sphereEl = document.createElement('a-sphere');
sphereEl.setAttribute('radius', 1);
document.querySelector('a-scene').appendChild(sphereEl);
sphereEl.addEventListener('loaded', function () {
console.log('sphere attached');
});
Entity-Component
https://aframe.io/docs/0.2.0/core/
A-Frame is built on an entity-component-system pattern (ECS), popular in game development and used in engines such as React and PlayCanvas. In ECS, every object (or entity) is created from the ground up by composing components (not to be confused with Web Components). Components add logic, behavior, appearance to entities.
https://aframe.io/docs/0.2.0/core/component.html
We can encapsulate JS within components:
AFRAME.registerComponent('color-on-click', function () {
schema: {
color: {default: 'blue'}
},
init: function () {
var el = this.el; // Reference to the entity.
var data = this.data; // Data passed in through HTML, defined in schema.
el.addEventListener('click', function () {
el.setAttribute('color', data.color);
});
}
});
And attach these components to our entities in HTML. Notice how we are declaratively attaching/plugging in JS to objects in HTML that can take inputs!:
<a-box color="red" color-on-click="color: blue"></a-box>
<a-sphere color="orange" color-on-click="color: white"></a-sphere>
And these components can do anything beyond simple JS. We have access to the entire three.js API so anything in three.js can be easily wrapped. In fact, we wrap any JS library in the world we want in components and use them declaratively.
Manipulating Components
Manipulating properties of components is similar to manipulating HTML attributes. <a-box> consists of geometry and material components. So it looks like under the hood:
<a-entity id="box" geometry="primitive: box" material="color: red" scale="2 2 2"></a-entity>
We can manipulate the individual properties:
var boxEl = document.querySelector('#box');
boxEl.setAttribute('geometry', 'width', 5);
boxEl.getAttribute('material').color;
boxEl.removeAttribute('scale');
Integration
By exposing its API in HTML, A-Frame works well with existing web frameworks and libraries like d3, React, Angular, templating engines.
aframe-react
d3 example
d3 in a-frame component
Related
I would like to add in a non-vue application a custom element.
For that, I've created a classical SFC :
//test.ce.vue
<template>
<div class="text-primary">Test</div>
</template>
<script>
export default {
name: 'test',
};
</script>
<style>
.text-primary {
color: red;
}
</style>
And then a main script :
//app.js
import Test from 'test.ce.vue';
const testElement = defineCustomElement(Test);
customElements.define('test-element', testElement);
document.body.appendChild(document.createElement('test-element'));
Everything is running normally with the creation of a shadow dom element :
<test-component>
#shadow-root (open)
<style>
.text-primary {
color: red;
}
</style>
<div class="text-primary">Test</div>
</test-component>
I would like to avoid to redefine .text-primary class in the component as this class is already defined in the main css file. I also don't need to define specific classes for this component only, so in other terms, I would like to remove the shadow dom like a classical custom element will do.
So basically, render this :
<test-component>
<div class="text-primary">Test</div>
</test-component>
Is there's any option to define in vue that permit that ?
Older question, but in case someone still needs a solution for this...
there is currently no way to tell Vue not to use the shadow-dom. In Vue 2 there was a official package for creating web-components without shadow-root. And there is a community port for Vue 3 of that:
https://www.npmjs.com/package/vue3-webcomponent-wrapper
It was only meant to help people who have just migrated from Vue 2 to keep there application working. It was never intended to replace the official solution and should only be used until the official package can handle Vue 3.
Unfortunately that never happend.
The community port still works, but the package does not contain any source code, so it is a bit scary to use.
I came up with another solution for our project. Using defineCustomElement on a more complex vue component wich is composed by a bunch of nested components reveals another problem. The css of the child components wont be copied to shadow root. So only the css of the root component will work.
You can find the related issue and a workaround with full example here:
https://github.com/vuejs/core/issues/4662#issuecomment-1116001438
It basically grabs the css from the head and appends it to the shadow root.
You just have to extend it to also copy your main.css, like
<template>
<div id="app" ref="injectionElementRef">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js + TypeScript App" />
</div>
</template>
<script lang="ts">
import {defineComponent} from 'vue';
import HelloWorld from './components/HelloWorld.vue';
export default defineComponent({
name: 'App',
components: {
HelloWorld
},
mounted() {
const el = this.$refs.injectionElementRef as HTMLElement
const root = el.getRootNode()
const linkTag = document.getElementById('main-css-id')
root.insertBefore(linkTag.cloneNode(), el)
}
});
</script>
The downside of this method is, there is a short flicker because the css is applied after mount. You could show an empty element till css is applied to work around that.
You are using Vue as a Tool to create Web Components, but why use a Tool over Native Technology?
Tools are not better; Tools are only faster in performing a task.
And in your case the Tool does something you do not want it to do.
Using native Web Components Technology, all you need is:
<style>
.text-primary {
color: red;
}
</style>
<test-component></test-component>
<script>
customElements.define("test-component", class extends HTMLElement {
connectedCallback() {
this.innerHTML = `<div class="text-primary">Test</div>`;
}
})
</script>
I am writing a custom component that I would like to define other component dependencies.
The dependencies are different animations types.
Let's say they have the names "animation__x" and "animation__y"
x and y can be any name, so I am looking for something like animation__*
or /animation__\s*/
The only way I have made this work at the moment is either ensuring my component is placed after the animation components on the HTML or alternatively to force update components using this.el.updateComponents()
Neither of these solutions feels right to me.
AFRAME.registerComponent('cool-component', {
dependencies: ['animation'],
update: functions(data){
//detect available animations and do some stuff with them
let animations = Object.keys(components).filter((key) => {
return /(^animation__\w*)/.test(key);
});
//animations results in an empty array
}
});
html that is not working
<a-scene cool-component animation__x="" animation__y="" animation__z=""></a-scene>
html that is working (but its not good as I cant ensure my component is always last in the list
<a-scene animation__x="" animation__y="" animation__z="" cool-component></a-scene>
js that works, but doesnt feel write as I am using the entities internal functions
AFRAME.registerComponent('cool-component', {
dependencies: ['animation'],
update: functions(data){
this.el.updateComponents(); //<-- I DONT LIKE THIS BUT IT WORKS
//detect available animations and do some stuff with them
//now all animations are available as this.el.components
let animations = Object.keys(components).filter((key) => {
return /(^animation__\w*)/.test(key);
});
}
});
Three options:
Depend on the specific component names: dependencies: ['animation__xxx']
Make cool-component set those animations:
AFRAME.registerComponent('cool-component', {
init: functions(data){
this.el.setAttribute('animation__xxx', {...});
}
});
You can also defer cool-component logic until the entity has loaded and all the components have initialized:
init: function () {
this.el.addEvenListener(‘loaded’, this.doStuffAferComponentsLoad.bind(this));
}
More details in what cool-component is trying to accomplish will help to get a more precise answer.
A-Frame Mixins go into the <a-assets> element, which must be defined before the scene is rendered. This makes sense for pre-loading/caching images, videos etc, but it seems there should be a way to dynamically create and use mixins.
Just adding the mixin to <a-assets> at runtime does not seem to work. The recommendation for adding image assets at runtime is to inline the image source and set it on the material directly. Is there some similar way of defining/altering a mixin at runtime? Or do I just need to set the relevant properties on all the objects to which the mixin is applied (taking care to also account for properties having been set by other mixins later in the mixin chain or directly on the object itself)
Edit: It looks like aframe-asset-on-demand-component is designed to do this for image/video assets. Unclear if works for mixins, but it also hasn't been updated in a year. Is this a (semi-)officially recommended solution?
Sorry if I've misunderstood your question but I seem to be able to add mixins to the assets tag at runtime. A basic version would mean writing a component as follows;
// add assets at run time
AFRAME.registerComponent('addasset', {
init: function () {
var assets = document.getElementsByTagName('a-assets')[0]
var mixin = document.createElement('a-mixin')
mixin.setAttribute('id', 'makeitred')
mixin.setAttribute('material', 'color: red')
assets.appendChild(mixin)
},
});
And then attach that component to the scene as follows;
<a-scene addasset>
<a-assets>
</a-assets>
<a-cylinder
mixin="makeitred"
position="0 0.5 -3">
</a-cylinder>
</a-scene>
Here is a working glitch
To demonstrate how that could be added once the scene is running here is a version of the same component with a setTimeout to demonstrate how the mixin could be added later on.
// add assets at run time, delayed
AFRAME.registerComponent('addasset', {
init: function () {
setTimeout(function(){
var assets = document.getElementsByTagName('a-assets')[0]
var mixin = document.createElement('a-mixin')
var cylinder = document.getElementsByTagName('a-cylinder')[0]
mixin.setAttribute('id', 'makeitred')
mixin.setAttribute('material', 'color: red')
assets.appendChild(mixin)
cylinder.setAttribute('mixin', 'makeitred')
}, 2000);
},
});
and then the HTML in which the mixin attribute will be added later
<a-scene addasset>
<a-assets>
</a-assets>
<a-cylinder
position="0 0.5 -3">
</a-cylinder>
</a-scene>
Here is a glitch of that
And for the sake of exploration, here is the same set up but triggered by an example event. First the same component but with an event listener
// add assets at run time, triggered by event
AFRAME.registerComponent('addasset', {
init: function () {
document.addEventListener("testevent", function(){
var assets = document.getElementsByTagName('a-assets')[0]
var mixin = document.createElement('a-mixin')
var cylinder = document.getElementsByTagName('a-cylinder')[0]
mixin.setAttribute('id', 'makeitred')
mixin.setAttribute('material', 'color: red')
assets.appendChild(mixin)
cylinder.setAttribute('mixin', 'makeitred')
});
},
});
Then a component that emits an event for testing
// test event to trigger adding of mixin
AFRAME.registerComponent('testevent', {
init: function () {
var self = this.el
setTimeout(function(){
self.emit("testevent")
}, 3000);
},
});
Then the HTML, as before but including a test entity that emits an event
<a-scene addasset>
<a-assets>
</a-assets>
<a-cylinder
position="0 0.5 -3">
</a-cylinder>
<a-entity
testevent>
</a-entity>
</a-scene>
And here is a glitch for that
So you could mix those up, add the mixin to assets but delay/trigger on event the addition of properties or add the mixin to assets with properties but delay/trigger on event the setting of that attribute on your target elements.
I hope that helps
i try to build an Cordova/Phonegap application using vue.js and the Framework7.
I find out how to use functions like "onClick" using the "v-on:click="OnClick" attribute in an html element. Framework7 has jquery already implemented in the dom.
But there is one question. How can i access the dom directly, so that i can select whole css classes with the jquery selector. Like:
$('.likeButton'). ?
In the offical framework7 i found something like this to access the dom with its functions:
this.$$ or this.Dom7
This is what i have already written down in the home.vue file:
<script>
//import Fonts-awesome Icons
import FontAwesomeIcon from '#fortawesome/vue-fontawesome'
import {} from '#fortawesome/fontawesome-free-solid'
import F7Icon from "framework7-vue/src/components/icon";
import F7PageContent from "framework7-vue/src/components/page-content";
import * as Framework7 from "framework7";
export default {
name: 'FAExample',
components: {
F7PageContent,
F7Icon,
FontAwesomeIcon
},
methods: {
clickit: function () {
console.log("hi");
//this is what i have tested, looking if i have access to dom
let $$ = this.$$;
console.log($$);
},
//this is what i want to use
$('.likebutton').on('click',function () {
})
}
}
</script>
Did any of you have an idea how this works?
I hope you can help me. I'm new with vue.js in combination with the framework7.
Thank's for your help :)
We can use all the DOM functions just like
this.$$('.classname)
for example, if you want to hide something by jquery you can use as:
this.$$('.classname).hide()
To check all the DOM functions you can check the official documentation.
https://framework7.io/docs/dom7.html
But make sure that your DOM function should not in any Window function.
If you get the error to implemented it, just make the 'this' instance first.
Just like:
var self=this; // a global variable with this instance
use
self.$$('.classname).hide()
for any framework7 help, just ping me on skyp: sagardhiman5_1
Have you tried using Vue's $refs? You can set a reference to a specific DOM element and then access that in Vue.
A simple example:
<template>
<div class="some-item" ref="itemRef">Some item</div>
</template>
Then in the component:
var myItem = this.$refs.myItem;
// do what you want with that DOM item...
You can also access $refs from the parent. The example in the link below gives details on that.
More on $refs: https://v2.vuejs.org/v2/guide/components.html#Child-Component-Refs
I have a react component:
React.createComponent({
render: function () {
return (<div className="some-component"></div>);
}
});
Some seconds after it renders, I want it to add a class from within the component. The class is for the purposes of revealing the component with an animation. I don't regard it as a real change of state, as it has no affect on the application other than to give the component an animated introduction, so I'm loathed to initiate it from outside of the component via a change of store/state.
How would I do this in simple terms? Something like:
{setTimeout(function () {
this.addClass('show'); //pseudo code
}, 1000)}
Obviously I could use jQuery, but that feels anti-React, and prone to side-effects.
I don't regard it as a real change of state, as it has no affect on the application other than to give the component an animated introduction
A change of state in the component seems the natural and proper solution for this scenario. A change in a component state triggers a re-render, which is exactly what you need here. Consider that we're talking about the state of your component, not of your application here.
In React, you don't deal with the DOM directly (e.g. by using jQuery), instead your component state should "drive" what's rendered, so you let React "react" to changes in state/props and update the DOM for you to reflect the current state:
React.createComponent({
componentDidMount () {
this.timeoutId = setTimeout(function () {
this.setState({show: true});
}.bind(this), 1000);
}
componentWillUnmount () {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
}
render: function () {
return (<div className={this.state.show ? 'show' : null}></div>);
}
});
When using setTimeout in React you need to be careful and make sure to cancel the timeout when the component gets unmounted, otherwise your timeout callback function will run anyway if the timeout is still pending and your component gets removed.
If you need to perform an initial mount animation or more complicated animations, consider using ReactCssTransitionGroup, which handles timeouts and other things for you out of the box: https://facebook.github.io/react/docs/animation.html