Vue3 documentation example codeblocks are strange - javascript

All throughout the Vue 3's documentation, they do the following when showing example code in a component:
Vue.createApp({})
I've never had to do this though, I simply use
<script>
export default {
name: 'example-component-xd'
}
</script>
What am I missing here? I just started learning Vue 3, and I haven't learnt any other versions of Vue before. This question is more just a curiosity I have, as it doesn't impact my ability to understand the documentation, but I thought that it may have something to do with the history of Vue, ES6 or best practices etc. Here is another example:

In Vue 3, Vue.createApp({}) replaces new Vue({}) from Vue 2. This line of code is typically in your entry file, where you mount the app (not in your component files).
The code in the <script> tag you showed is for single file components, and you can continue using that style. Never would you use Vue.createApp() or new Vue() in those single file components.
You can checkout an example Vue 3 app that shows Vue.createApp() in src/main.js, while the single file components in src/components use the Options API that you're also using.

Related

Visual builder to work with manually hard-coded templates/components

I wonder, is it possible to create a visual no-code builder to work with JS components (e.g. React JSX) if them are manually hard-coded before?
Let me explain what I mean.
Suppose a simple React component pages/index.js previously written by a developer manually:
function HomePage() {
return <div>Welcome to Next.js!</div>
}
export default HomePage
How can we change such a component in the front-end using a visual builder?
For example, we want to add a new HTML element (e.g. H1) inside the existing div.
As I can understand, the builder first needs to know in which JS file the HTML markup is stored to update it. So we can add id="homepage" to the div first and then store a relation as a config like
{"homepage": "pages/index.js"}
And now if we add a new element inside <div id="homepage">, the builder adds the element to the DOM of the div at the client, then takes the whole updated DOM of the div and writes back to the file index.js according to the config
Ok, but the file contains not only HTML markup - it's JS (React) code.
How to keep all the JS code e.g. function HomePage(), return, export default and so on ?
As an option, we can separately load all the JS code as HTML including non-HTML code as #text nodes. Then update the DOM and re-write everything back to the file.
But it sounds complicated and may cause unexpected issues.
So what solution would be the best?
Or maybe there is a ready React-specific solution?
Or maybe it's a bad idea at all to parse and re-write manually hard-coded components by visual builder and the only solution is to store everything as JSON like "homepage":{"div", {"class":""}, "Welcome..."} which is more easy for re-writing ? (but requires a new render)
It depends
I believe the answer that you are looking for very much depends on the level of flexibility that you want your no-code builder to have.
Depending on that, your project could benefit of the trade-offs and advantages of different solutions.
Let's briefly remember that basically a React component will need some props that then will be taken through a render template and output a working HTML. This is assuming a basic case where you don't need your react components to be smarter. Additionally, JSX is just sugar coating over function calls, so you could basically just compose functions to output a React component independently of using the JSX syntax. Hence no need to declare HTML, just changing the output of your no-code tool to JS instead of HTML.
For example, if you can modify how the no-code tool render, you can specify that when moving an element inside another you basically:
Highly Flexible & Customisable
In a highly flexible setup, I will recommend going through the last option you numbered, having a Data-Driven UI is the most common of the cases for complex systems. For example, Figma has an option to export the designs as react components, you can read how they do it here. Basically they take the tag output from figma which is a JSON of tags and create some React componets using templates. If you define "you own UI language" you could have quite a good control over what blocks you can build and define the way of interacting with them (e.g. adding a img component could be quite easy if you know the props and what it needs to render, then creating a React template for it is easy).
Limitations: you require to plan quite well the API of the parser and interaction between different sets of items.
Simple no-code builder
For simpler scenarios you could go with the first approach that you mention, you won't even need to add ids, some tools like React Developer Tools can already inspect the VirtualDOM to understand which part of the render belongs to which React Element (using react internals, which could take some time to understand, but for example you can inspect in the rendered how they use the data-reactid for identification). Knowing this, you can already define the template functions for the render() method (so the JSX output), and separate it code wise, so that when you generate the code, the HTML template is split from the React code as much as possible.
Silly example of how it could look:
// htmlBlockTemplate.js
export const helloPageTemplate = (props) =>
`<div> <h1>${props.title}</h1> </div>` // This can be generated from the `no-code`
// page.jsx
export const Page = (props) => {
return helloPageTemplate(props)
}
Using functions it could look like:
const Page = (props) =>
return React.createElement('div', null,
React.createElement('h1', title: prop.title, `The title ${title}`)
);
}
Limitations: eventho you could, adding custom components (like another React Component or a web component), it becomes more difficult since you will also have to deal with the import graph and probably.
Inevitably you will need to tweak how the render of the component works (rather by creating a parser from your UI language, or changing how the react component is written. If you have a good control of AST, then writing a parser for either of the cases should not be a problem.

Structuring vue js files

This is probably a very basic question so bear with me I come from a jquery background and I'm a bit confused on how to structure code in Vue.
I have a laravel project set up with vue.js so one app.js file.
Let's say I have a set of directives in that app.js for registering a user :
const app = new Vue({
el: '#app',
data: {
errors: [],
email:null,
first_name:null,
last_name:null,
...
},
methods:{
register: function (e) {
//Do stuff
}
});
Now what if I now want to write code for another page, let's say a crud application to list the users where should I write the Vue code ?
I guess I could add to my app.js file but I will soon end up with a huge app.js file and I do not want to expose methods in pages that do not require them.
What is the correct way of doing this, I guess there must be some kind of routing going on somewhere ?
In Vue, you can make use of components for implementing different pages ad even inside a page you can then make child components.
Each component consists of the template i.e., HTML code, script, and its respective style.
Making use of components makes the code more maintainable, reusable, and understandable.
You can check this link for understanding more about the components: https://v2.vuejs.org/v2/guide/components.html
For routing, there is an official router for Vuejs which is Vue router. You can find more on the router on https://router.vuejs.org/.

Can I use a React app as a component on a static HTML page

I'm new to React and JS, and working with react-csv-viewer.
It works as expected and I can build and deploy it on a local server. But I do not require this, I just want to integrate the app as a component of a static HTML page.
I've tried following the process listed on the React tutorial for this, but I have trouble understanding the build process and how can I achieve this.
All I wish to achieve is to be able to use <CsvViewer /> provided by the author, possibly like this
const rootElement = document.getElementById("root");
ReactDOM.render(<CsvViewer />, rootElement);
and get the viewer app rendered at my HTML file, without building and deploying the viewer app on a (local) server.
Will appreciate any help or hints in this regard.
You can add React as it was shown in the tutorial you linked. The downside is that, you can't use JSX syntax (as it should be converted to JS during build time as it's not recognized by browsers as so).
Here is a post explaining how you can do so without transpilaton steps.
https://codepen.io/alexkrolick/post/react-without-a-build-step
Alias React.createElement, and call it to create components.
e.g.)
const h = createElement // convenient alias
// Instead of
<div className="foo" />
// create an element like so
h("div", { className: "foo" })
For more info on how that works, check out the official documentation.
https://reactjs.org/docs/introducing-jsx.html#jsx-represents-objects
But I really doubt anyone writes React code that way without a transpilation step in real life.
Would creating a separate site/page with React be a problem by chance? You can check out ParcelJS to easily create a React site if you aren't familiar with transpilation.

Is it possible to build a Standalone Vue app?

Is it possible to build a Vue app, which does not require Vue as as a dependency at runtime?
I.e. instead of the browser having to load the vue.js and the app like this
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://www.myxyzhost.com/my-app.js"></script>
have a my-app.js which already includes vue.js, so that including the script in a web page becomes a simple one liner?
<script src="https://www.myxyzhost.com/my-app.js"></script>
So, it was actually simpler than I thought:
I just created a separate entry file for webpack to consume like
my-custom-component-entry.js
and slammed everything I needed in there (vue and the respective component):
// This is the actual solution, I was looking for.
import Vue from 'vue';
import MyCustomComponent from './components/my-custom-component.vue';
new Vue({
components: {
'my-custom-component': MyCustomComponent
}
}).$mount('#app'); // ya gotta have a #app element somewhere of course
And then I built it with webpack (I am not going into detail here).
Now everything is packed in on file. No separate Vue runtime, which a customer might need to install. All that's necessary is:
<script src="https://www.myxyzhost.com/dist/my-custom-component.js"></script>
And yes, as always, this screws up, if you don't add the proper polyfills for internet explorer, but I take that for granted.
The important thing: for modern browsers it's a one liner which makes it easier to sell. That was all I needed.

AngularJS Directive into React App

We are looking at writing a new app using React but will need some existing Angular Directive that are specific for our business, for example a modified Angular Date Picker for example. There are many components so we won't be able to rewrite them all.
I am wondering if anyone has experience or knows the effort or feasibility of this?
The only article I've managed to find on this so far has been. Most resources I find mention going the other way from an Angular App with added React. http://softeng.oicr.on.ca/chang_wang/2017/04/17/Using-AngularJS-components-directives-in-React/
There's a library called angular2react that makes possible reuse angularjs code inside react components. You can see if it fits your needs. :)
I have written a simple demo app showcasing how to achieve it: react-angularjs-bridge
The basic steps are as follows:
Create a react component that is going to host the angular component in the DOM. This component should always render a simple html element (eg. a HTMLDivElement) so that react does not get confused when reconciling the virtual DOM with the real DOM.
After the react component was mounted componentDidMount, create a shadow root under the rendered HTMLDivElement and initialise the angular application under it. This will ensure that the angularJS component is encapsulated and is not affected by the react application and vice-versa
Click here for a demo. Check how the react application styles do not impact the styles of the angular component.
Independently of Angular, ref is a way to go: it gives to access to an underlying DOM node and the ability to manipulate the DOM inside that node in any way you like, including AngularJS. Your changes will stay - at least until react clears the component altogether.
You can create a ref in react by
<divOrAnyOtherDom ref={((el) => {this._elem=el;}).bind(this)}></...
(for the full description and alternate ways to the same end see here: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs)
Anyway, as you now have a DOM node, you can start working with it, i.e. adding angular to the mix inside componentDidMount. Sadly, this is not really obvious - here's a way that has worked for me in the past (moduleName needs to be a module you have put in place already with your logic):
let baseElement = angular.element(this._elem);
let templateElement = angular.element(templateSource);
angular.injector([ 'ng', moduleName ]).invoke(function($compile, $rootScope) {
let cmp = $compile(templateElement);
scpe = $rootScope.$new(false);
scpe.varname = whateverYouHave; # point is: you can set scope variables
cmp(scpe);
baseElement.append(templateElement);
scpe.$digest();
});
Now you have angular inside the DOM node react gave you.
(I've taken this from a slightly different integration: Vaadin to AngularJS, but the principle is the same: Vaadin, just like react, gives you a DOM node. When you're interested in the full code: https://github.com/akquinet/vaangular/blob/master/vaangular/src/main/resources/de/akquinet/engineering/vaadin/vaangular/angular/NgTemplate.js)
Plus: For any callbacks from the angular component, you'll likely have to use setState et al.

Categories

Resources