I'm pretty new to Vue and I'm trying to create my first app with it (I have worked through a whole tutorial though so it's not like I'm completely new to it). I come from a Java/Grails background so this new "frontend oriented webapps" is still pretty confusing to me. I'm using Vue 2 with webpack.
The problem I'm having is running methods when the app initializes which creates data in the App.vue component (which I'm assuming is the root component, is that correct?) and then accessing this data in child components. So specifically what I'm trying to do is on in the 'created' life cycle hook I want to check if the user is logged in or not and then I want to update my navbar accordingly (show a login button if not, else show the user's name, for example).
I haven't even quite figured out how exactly I'm gonna determine if the user is logged in yet coz so far I've only been trying to create dummy data in the App.vue component and then accessing it in child components. Everywhere that I've researched says that I should use an event bus but (I think) that's not gonna work for me (correct me if I'm wrong) coz the only examples I can find is all $emit functions being called on user events (like button clicks) and I want it to have the data globally accessible (and mutate-able) everywhere all the time.
So I'll try to show you some code of what I had in mind:
App.vue:
...stuff...
data() {
return {
authToken = '',
userdetails = {},
loggedIn = false
}
},
created: function() {
// check browser storage for authToken
if(authToken) {
// call rest service (through Vue Resource) to Grails backend that I set up
// beforehand and set this.userdetails to the data that gets returned
if(this.userdetails) {
this.loggedIn = true;
}
}
}
...stuff...
Home.vue:
<template>
<div class="home">
<nav-bar></nav-bar>
</div>
</template>
...stuff
NavBar.vue:
<template>
<div class="navBar">
<div v-if="loggedIn">Hi {{ userdetails.name }}</div>
<div v-else>Please log in before continuing.</div>
</div>
</template>
Please excuse if any of that code has any mistakes in it, it's just to show more or less what I'm trying to do and I made most of it up right now. So the main question: How do I go about getting the v-if="loggedIn" and {{ userdetails.name }} part to work (coz obviously the way it's set up now that won't work, right?). And then besides that, any general advice on "global variables" and data flow in Vue js will be appreciated coz I believe that my server-side app mentality might not work in front-end javascript apps.
To get Data from parent component you can use this.$parent.userdetails in the child component.
But a much better way is to use props like this
https://v2.vuejs.org/v2/guide/components.html#Passing-Data-with-Props
Lite pattern, not for complex sharing tasks
You can access global app component everywhere (routes, components, nested components) with the predisposed field:
this.$root
Notes for overengineers: It is officially suggested as "lite" approach in vue guide: https://v2.vuejs.org/v2/guide/state-management.html.
Obviously, it is not a architectural patternized solution, but ok for just sharing a variable or two.
In these case this lean approach avoids developer to import a full sharing framework like vuex, heaving development, know-how requirement and page download, just for such a trivial sharing task.
If you dislike lite approaches, even when appropriated and officially suggested, maybe is not how to share the problem, but which framework to use.
For instance, Angular is probably best fitted for heavy engineered approach, and I not mean one is better than the other, I mean different instruments suite best for different task and approaches, I too use it when need to realize a heavier and more complex solution, in these case even with vuex I could not handle all the components interaction and realtime data sharing.
Following methods are not recommended by other developers or vue itself.
this.$root;
or
this.$parent.userdetails
In my opinion the best way to share any data across components is using vuex state management.
Here is the official documentation link: https://vuex.vuejs.org/#what-is-a-state-management-pattern
Related
I have a simple, probably silly doubt about this basic thing using Vue not for an SPA:
Considering that Vue in my project is used to make small pieces interactive (tables, lists), and general filtering of database records, should I create a Vue instance for every component and add <div id="app"> in the places I need those things
...
<body>
....
<div id="nav">...
....
<div id="app">
<component></component>
</div>
app.js
const table = new Vue...
const calendar = new Vue...
Or should I make a generic #app div right after the body tag, containing all the site and, inside that, inserting the single components to then manage everything in a single new Vue instance?
<body>
<div id="app">
<div id="nav>....
</div>
<div id="anotherDiv">
...
...
</div> <!-- #app div -->
</body>
app.js
const app = new Vue...
It is probably easier to have a generic #app in your root div that will contain all of your site. Then if you want to add more components, then all you have to do is create a vue component and register it. To register a new component to your Vue instance you can use the following code where you create a main.js file.
Vue.component('your-component-name', require('PATH TO YOUR COMPONENT'));
After your component is registered you can use it anywhere in the #app body.
There are many things to consider here and all answers will be somewhat subjective, so keep that in mind. I don't think that any single way is the "correct" way to do it. I have found that the simplest implementation is to have a single Vue instance in app.js, and then build your components and use them wherever you want in the app div. However, this can be overkill and may affect you negatively in a couple of ways.
As one example, if you are not 100% committed to using Vue, then it's most likely that you also want to use jQuery and maybe even some jQuery plugins somewhere else in your app. jQuery and Vue do not play very nicely together unless you are instantiating the jQuery within Vue components. For this reason, if you plan to utilize other javascript libraries such as jQuery, then you might consider using individual instances of Vue with smaller scopes wherever you need to use a component.
If, however, you use Vue to help with some global tasks, such as line-clamping or truncating, then you really are best served by having a global install.
As far as other considerations, such as overhead, I believe that either method would probably just about be even. When you load globally, you get the benefit of browser caching even though the script is on each page. When you load page-by-page, you get the benefit of not having to load the scripts everywhere and only using them as you need them. In either case, overhead is pretty minimal for Vue on the modern web, so I don't think this should play into your decision at all.
Those are my thoughts.
You can do like this:
// Imported components
import examplecomponent from './components/ExampleComponent.vue';
import adduser from './components/AddUser.vue';
and for call vue components in laravel view:
<div id="app">
<examplecomponent ></examplecomponent>
</div>
<script src="{{asset('js/app.js')}}"></script>
For more basic information:
Laravel and VueJS - where\how to put instance and components
I keep getting this same error. My code is shown here:
https://codesandbox.io/s/88o66kkyz9
For those who need an idea of what it does, it gets lists of IPs from a websocket in the main Vue.js. I want to create a component to layout information about the IP so I can just iterate through that in the app.vue render template I know this is basic, but I'm really new to vue. but god, so much better than angular messiness to me.
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.
I am trying to make sense of some code snippets in javascript. But getting way too confused, it seems to be using all the symbols in all possible ways.
import Ember from 'ember';
export default Ember.Route.extend({
metrics: inject.service(),
activate() {
this._trackPage();
},
_trackPage() {
run.scheduleOnce('afterRender', this, () => {
const page = document.location.href;
const title = this.routeName;
get(this, 'metrics').trackPage({ page, title });
});
}
});
q1: What are the keyword service, get, extend? What are they doing here?
q2: Why is activate defining _trackPage separately? Why not put the reschedule code in activate() itself?
Basically trying to understand: https://emberway.io/applying-the-adapter-pattern-for-analytics-in-ember-js-apps-29448cbcedf3
A service is a place to put code that can be used almost anywhere in the app. In order to make the code inside a service available to the script you're working on, you inject it.
get is a helper that is used to access things like the service or Ember objects. In more recent tutorials, you'll see syntax that looks more like this.get('metrics'). See the docs here.
You could put the _trackPackage code into the activate function if you wanted to. However, activate is a special function called a hook, and many developers like to keep their route hooks like activate as short and sweet as possible for stylistic reasons. Hooks are special functions that fire automatically on things like a user entering a route, rerenders, etc. There are many kinds of hooks like this throughout Ember.
Extend is Ember boilerplate that gets created for you when you use the Ember CLI to make new files. Basically, when you create a route, you're extending on Ember's default route configurations, attributes, and methods. So there's some base behavior (like the activate hook) that gets inherited.
I recommend that you read the Ember Guides sections on objects and services for more info.
I am currently building an application in polymer 1.7 with firebase integration. The integration also uses iron pages from the starter kit.
My question is to understand the best archtectual pattern available or adopted for best usage.
index.html: <app></app>
app.html:
<firebase-app>
<firebase-auth>
<firebase-document> (query)
<firebase-document> (query)
<iron-pages>
<profile uid="[[user]]" data="[[data]]">
<login uid="[[user]]">
<contact>
<latest data="[[data]]">
I have built in page switcher, which works fine but passing in the user bind every single time if i want to authenticate the page seems convoluted.
Furthermore, i want to separate it out so a query is run within the component, it gets all the information it requires. I am currently building a massive app.html and it doesnt seem write with web components principles.
Whats the recommendation?
You can use <iron-meta> component to share information across dom tree and <iron-meta-query> to get this data.
For instance, you can have iron-meta defined in your parent component
<iron-meta id="data" key="shared" value='{
"id": "1"
}'>
</iron-meta>
Then to get data in some of your children use
<iron-meta-query key="shared" value="{{sharedValue}}">
For more information about using <iron-meta> component see Polymer documentation