Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

Tei posted:

I dont think is a good idea to use ternary for long expressions / multiline.

Ternary exist to have a more compact format where is still readable. To protect the surrounded code from some meaningless if that will only obscure why the code is doing what is doing.

Anyway nothing is forbidden, everything is free, have fun and happy coding. Somebody somewhere has found CSS is turing complete and is compiling a bitcoin miner for it.

Ternary is a shorthand that is particularly nice when the logical fork that results from the condition is purely a different assignment to the same variable (or return statement), rather than an actual branch in the business logic. For one, it ensures that the result of the condition, be it true or false, necessarily results in the LHS being assigned something, even if that 'something' is null.

But yeah, it's a case-by-case thing I think, there's no real hard and fast rule that I follow, I just kind of look at it at the time and go "yeaaahh, that's looking a bit gross, I'm sure it would be more readable as an if/else".

Adbot
ADBOT LOVES YOU

Love Stole the Day
Nov 4, 2012
Please give me free quality professional advice so I can be a baby about it and insult you

rohan posted:

React 16 introduced the <Fragment> tag, which goes some way to fixing this -- it groups the nodes for return but doesn't render, so the resulting DOM tree doesn't have unnecessary parent divs.

(React 16.2 introduced <> as a shorthand notation, as well.)

I think that this is not compatible with TypeScript JSX? Because my compiler yelled at me for trying to use these tricks.

HaB
Jan 5, 2001

What are the odds?
:words: about ternary ops from various people


Anony Mouse posted:

code:
render() {
	return (
		<div>
			{
				this.props.foo
				?
					<div>
						<h1>bar</h1>
						<p>baz</p>
					</div>
				:
					[]
			}
		</div>
	);
}

A multiline ternary except in a VERY rare case would fail code review in every shop I have ever worked in, regardless of the language. There's a sentence in your post which is very telling:

quote:

it's readable for me cause it's what I'm used to by now

As someone who has never seen your code before - that looks like whitespace HELL to me first, then when I finally realize that the mysterious ? and : just sort of floating out there is a ternary operator, I can feel the hives start raising on the backs of my arms.

After nearly 20 years as a developer, this axiom has been firmly beaten into my (arguably thick) skull: readability above ALL else. Period.

You may not have had the experience yet, but at some point you will be looking at some Weird poo poo(tm) in a code file somewhere and think "what the hell is this guy doing here?" only to realize a few minutes later that "this guy" was YOU a year ago, and it's because of stuff like that code block up there.

code:
var fart = someBool
    ? some really long expression
    : some really long expression

or sometimes

var fart = 
    someBool
    ? some really long expression
    : some really long expression
I can almost tolerate this, except it seems like such a personal style quirk that who ever comes along afterwards is bound to add their own personal style to it and it's just gonna get worse and worse. A MUCH easier rule is: no multiline ternaries. What you lose in typing an extra 10 characters you more than make up for in readability.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

HaB posted:

code:
var fart = someBool
    ? some really long expression
    : some really long expression

or sometimes

var fart = 
    someBool
    ? some really long expression
    : some really long expression
I can almost tolerate this, except it seems like such a personal style quirk that who ever comes along afterwards is bound to add their own personal style to it and it's just gonna get worse and worse. A MUCH easier rule is: no multiline ternaries. What you lose in typing an extra 10 characters you more than make up for in readability.

To be clear, my goal IS readability. I'm not worried about typing extra characters. As mentioned there are other conceptual benefits to using ternaries too. I think the examples I used are perfectly readable in the form that I posted them.

rohan posted:

Christ, this. I'm working with someone who I think has just discovered ternaries and the entire codebase is littered with things like:
code:
const foo = isActive
                     ? 'show'
                     : 'hide';
It's taking a lot of self-control not to go through and change everything to <Component className={ isActive ? 'show' : 'hide' } />

The multiline thing for that example is just stupid, but otherwise that's a perfect use-case for a ternary I would have thought? Is it just the multiline thing that bothers you? Because that I get.

putin is a cunt fucked around with this message at 14:00 on Mar 8, 2018

HaB
Jan 5, 2001

What are the odds?

a hot gujju bhabhi posted:

To be clear, my goal IS readability. I'm not worried about typing extra characters. As mentioned there are other conceptual benefits to using ternaries too. I think the examples I used are perfectly readable in the form that I posted them.

The multiline thing for that example is just stupid, but otherwise that's a perfect use-case for a ternary I would have thought? Is it just the multiline thing that bothers you? Because that I get.

Perfectly readable to you because you are used to writing them and reading them that way. Other devs you work with might not think so. Once again - every shop I have worked in would fail a multiline ternary on a code review, because you gain NOTHING by using multiline ones.

No one is arguing against using ternary - we are arguing against using multiline ones. There's not a conceptual difference between ?: and if/else at all. ?: is designed to be a quick single line shorthand:

code:
if(derp) {
    a = 1;
} else {
    a = 2;
}

vs

a = derp ? 1 : 2; 

is no contest, but:
code:
var fart;
if(someBool) {
    fart = some really long expression
} else {
    fart = some other really long expression
}
is much more explicit, readable and "conceptually" exactly the same thing as using ?:

The issue you stated was ensuring that the LHS gets assigned something. So why not:
code:
var fart = some other really long expression;
if(someBool) {
    fart = some really long expression;
}
because now I don't have to wonder at all, since I can see it getting explicitly assigned without having to chase down what the conditional is doing.

Tei
Feb 19, 2011
Probation
Can't post for 3 days!
I must write this because I am not a good person

code:
var someBool = 0;
...

function getErrorMessage(){
   return "<h1>Something bad</h1>";
}

function getOkMessage(){
  return "<span>Okay, bro</span>";
}

var messages = [  getErrorMessage,  getOkMessage ];

// Any "If" can be turned into a array
var fart = messages[someBool]();

Tei fucked around with this message at 15:14 on Mar 8, 2018

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

HaB posted:

Perfectly readable to you because you are used to writing them and reading them that way. Other devs you work with might not think so. Once again - every shop I have worked in would fail a multiline ternary on a code review, because you gain NOTHING by using multiline ones.

I doubt they're very common in JavaScript (and I don't use them there) but they're not uncommon in C# which is what I code in day-to-day. You personal workplace anecdotes aside, I didn't make this up and it is a thing I've seen other people do also.

HaB posted:

There's not a conceptual difference between ?: and if/else at all. ?: is designed to be a quick single line shorthand:

Of course there is, and I already explained this. A ternary signals immediately to the reader that the left hand side will be assigned something because that way a ternary does, an if/else statement doesn't because it's used for controlling logical branching. I don't understand how you can honestly try to claim there's no conceptual difference between the two.

HaB
Jan 5, 2001

What are the odds?

a hot gujju bhabhi posted:

I doubt they're very common in JavaScript (and I don't use them there) but they're not uncommon in C# which is what I code in day-to-day. You personal workplace anecdotes aside, I didn't make this up and it is a thing I've seen other people do also.


Of course there is, and I already explained this. A ternary signals immediately to the reader that the left hand side will be assigned something because that way a ternary does, an if/else statement doesn't because it's used for controlling logical branching. I don't understand how you can honestly try to claim there's no conceptual difference between the two.

Because there literally isn't. This code is equivalent:
code:

var a = test ? 1 : 2;

vs

var a = 1;
if(test) {
    a = 2;
}
So you explain to ME the difference. Ternary is nothing but shorthand/syntactic sugar.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

HaB posted:

Because there literally isn't. This code is equivalent:
code:

var a = test ? 1 : 2;

vs

var a = 1;
if(test) {
    a = 2;
}
So you explain to ME the difference. Ternary is nothing but shorthand/syntactic sugar.

They are not equivalent. I've already explained why. We're not going to agree and that's okay.

Gildiss
Aug 24, 2010

Grimey Drawer
Reposting an old gem from my last job.

Gildiss posted:

Another gem in the ESLinting mines.


code:
function(a,b){
    return (((typeof a.lastName === 'string' ? a.lastName.toUpperCase() : '') < (typeof b.lastName === 'string' ? b.lastName.toUpperCase) : '')) ? -1 : (((typeof a.lastName === 'string' ? a.lastName.toUpperCase() : '') > (typeof b.lastName === 'string' ? b.lastName.toUpperCase) : '')) ? 1 : 0));
}
Just because you can do something doesn't mean you should.

E: lol the blame shows this as being from one of the contracting teams tech leads.

darthbob88
Oct 13, 2011

YOSPOS

Tei posted:

I must write this because I am not a good person

code:
var someBool = 0;
...

function getErrorMessage(){
   return "<h1>Something bad</h1>";
}

function getOkMessage(){
  return "<span>Okay, bro</span>";
}

var messages = [  getErrorMessage,  getOkMessage ];

// Any "If" can be turned into a array
var fart = messages[someBool]();
No, no you are not a good person. Although I think you can "improve" that by making messages a dictionary, so you can key off of other/worse things than a bool.

prom candy
Dec 16, 2005

Only I may dance
Multi-line ternaries in JSX seem to be pretty common because there's no other real way to do if/else in that context. They are usually an indicator that you need to break your component into smaller components, but not always. Also that indenting above is outrageous, I don't normally care about that kind of thing but I should be able to have two code panels open side by side on a 1080p monitor and not have to side-scroll any code.

Capri Sun Tzu
Oct 24, 2017

by Reene

Anony Mouse posted:

code:
render() {
	return (
		<div>
			{
				this.props.foo
				?
					<div>
						<h1>bar</h1>
						<p>baz</p>
					</div>
				:
					[]
			}
		</div>
	);
}
This almost looks like ascii art

HaB
Jan 5, 2001

What are the odds?

prom candy posted:

Multi-line ternaries in JSX seem to be pretty common because there's no other real way to do if/else in that context. They are usually an indicator that you need to break your component into smaller components, but not always. Also that indenting above is outrageous, I don't normally care about that kind of thing but I should be able to have two code panels open side by side on a 1080p monitor and not have to side-scroll any code.

I didn't mention the indenting because I chalked it up to forums formatting instead of his own because lol who uses an 8 space indent?

Vincent Valentine
Feb 28, 2006

Murdertime

The only time I end up using multi like ternaries it's due to having other similar expressions that all do similar but slightly different things, except this one just happens to be a little more complicated.

Like filtering a results set. Filtering by name and then setting state to reflect it is a simple ternary. Date is the same. Filtering to only show results about cars with v8 engines when there are also results about ice cream and fish requires a longer expression.

By making that a multiline ternary it signals that it's doing the same thing as all the other ternaries, it just happens to have more complicated logic. Putting it in an if else when all the others are ternary might make the reader think it's special.

Other than that, though, I try to avoid it.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

prom candy posted:

Multi-line ternaries in JSX seem to be pretty common because there's no other real way to do if/else in that context. They are usually an indicator that you need to break your component into smaller components, but not always. Also that indenting above is outrageous, I don't normally care about that kind of thing but I should be able to have two code panels open side by side on a 1080p monitor and not have to side-scroll any code.

HaB posted:

I didn't mention the indenting because I chalked it up to forums formatting instead of his own because lol who uses an 8 space indent?

Yeah I don't think the indenting is intentional, for some reason the code block makes tabs 8 spaces.

Love Stole the Day
Nov 4, 2012
Please give me free quality professional advice so I can be a baby about it and insult you
I want to apologize to everyone reading this thread right now for starting this ternary discussion. I was only trying to help!



Capri Sun Tzu posted:

This almost looks like ascii art
Funny that's also what I say when I read your posts hey buddy have a good night.

Ape Fist
Feb 23, 2007

Nowadays, you can do anything that you want; anal, oral, fisting, but you need to be wearing gloves, condoms, protection.
Today myself and my co-worker discovered there's a loving bunch of coffeeScript style syntax in our Angular2 application all over the place and it wasn't causing issues because Angular2 is a champ and just deals with it but it's loving dumb and someone should get fired for it. (We know it was you, Aaron.)

smackfu
Jun 7, 2004

We discovered today that IntelliJ doesn’t think Angular’s Location needs an import in Typescript because it’s also the name of the interface for stuff like window.location. The typescript compiler also has no complaint.

But the Angular AOT compiler does complain... and prints a completely useless error message. Just what I expected all around.

Vincent Valentine
Feb 28, 2006

Murdertime

Love Stole the Day posted:

I want to apologize to everyone reading this thread right now for starting this ternary discussion. I was only trying to help!

I like to think this is what my coworkers say behind my back about my code, so it allows me to find out whether I agree with arguments and should make changes or disagree and stay the course. v:shobon:v

SimonChris
Apr 24, 2008

The Baron's daughter is missing, and you are the man to find her. No problem. With your inexhaustible arsenal of hard-boiled similes, there is nothing you can't handle.
Grimey Drawer

IAmKale posted:

Does VueJS have a concept of a "service"? I'm trying to figure out how to initialize a singleton class to wrap an API and manage auth credentials and use it across multiple components and pages. If I just use a regular "import...from..." when I want to use the class of course it won't preserve state and I'll have to initialize it every time.

I don't know anything about VueJS, but the following works for preserving state in ES6 modules:

Service.js:
code:
var state = {}

export default {
  getState() {
    return state;
  },
  setState(newState) {
    state = newState;
  }
}

geeves
Sep 16, 2004

rohan posted:

React 16 introduced the <Fragment> tag, which goes some way to fixing this -- it groups the nodes for return but doesn't render, so the resulting DOM tree doesn't have unnecessary parent divs.

(React 16.2 introduced <> as a shorthand notation, as well.)

Christ, this. I'm working with someone who I think has just discovered ternaries and the entire codebase is littered with things like:

I'm fine with ternaries like that. I'd rather not have expressions inside props unless absolutely necessary. But that's just personal preference.

Speaking of React, some lifecycle changes are planned for the starting with 16.3 and .4 to lead up to 17.0.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
The formatting rules that VSCode are enforcing conflict with the TSLint rules that my webpack vue-cli project are using, causing a million warnings to fly out with every build and making me go insane.

Can I point VSCode to the tslint file in my project?

my bony fealty
Oct 1, 2008

Anyone regularly use Mithril? I'm intrigued by how simple the syntax looks and it feels like it would be fun to use. Does it get much use anywhere outside of the personal interest level?

Think I'll try redoing one of my simple React projects in Mithril.

rohan
Mar 19, 2008

Look, if you had one shot
or one opportunity
To seize everything you ever wanted
in one moment
Would you capture it...
or just let it slip?


:siren:"THEIR":siren:




geeves posted:

I'm fine with ternaries like that. I'd rather not have expressions inside props unless absolutely necessary. But that's just personal preference.
I think if you're using a ternary for purely presentational purposes, it should just be used inline in the className prop. There's no reason to declare a variable that's only ever used once, especially if it's only used in the render method. (Except when there is, but I'm not seeing any evidence, in this codebase at least, that there's any sort of case-by-case consideration happening. I think it's just holy poo poo, ternaries just like when I discovered functional programming and started throwing monads into everything.)

Sorry for bringing ternary talk back :(

Tei
Feb 19, 2011
Probation
Can't post for 3 days!

rohan posted:

There's no reason to declare a variable that's only ever used once, especially if it's only used in the render method.

A exception to this is to abuse bool variables to deofuscate long IF conditions by giving semantics to parts of the conditions.

code:

var package_arrived = ( package.address_code == local.address_code);
var package_required_truck =  (package.weight > 80 );

if( package_arrived && package_required_truck ){
     truck.sendAndCollect(package);
}

vs

code:

if( ( package.address_code == local.address_code) && (package.weight > 80 ) ){
     truck.sendAndCollect(package);
}

Tei fucked around with this message at 13:11 on Mar 13, 2018

Capri Sun Tzu
Oct 24, 2017

by Reene

Tei posted:

A exception to this is to abuse bool variables to deofuscate long IF conditions by giving semantics to parts of the conditions.

code:

var package_arrived = ( package.address_code == local.address_code);
var package_required_truck =  (package.weight > 80 );

if( package_arrived && package_required_truck ){
     truck.sendAndCollect(package);
}

vs

code:

if( ( package.address_code == local.address_code) && (package.weight > 80 ) ){
     truck.sendAndCollect(package);
}

I'm a big fan of this approach, and the general concept of using 'extraneous' variables to keep code readable.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

SimonChris posted:

I don't know anything about VueJS, but the following works for preserving state in ES6 modules:
Thanks for this! I ended up creating my API client as a typical Vuex module and everything fell into place better than expected.

prom candy
Dec 16, 2005

Only I may dance
Whole other can of worms here but I find setting a hard character cap on lines is a good way to figure out when it's time to extract logic into its own variable. And yes, creating "extraneous" variables with good names is just one more way to make your code readable and understandable.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

Tei posted:

A exception to this is to abuse bool variables to deofuscate long IF conditions by giving semantics to parts of the conditions.

code:

var package_arrived = ( package.address_code == local.address_code);
var package_required_truck =  (package.weight > 80 );

if( package_arrived && package_required_truck ){
     truck.sendAndCollect(package);
}

vs

code:

if( ( package.address_code == local.address_code) && (package.weight > 80 ) ){
     truck.sendAndCollect(package);
}


I completely support this approach.

Vincent Valentine
Feb 28, 2006

Murdertime

Tei posted:

A exception to this is to abuse bool variables to deofuscate long IF conditions by giving semantics to parts of the conditions.

code:

var package_arrived = ( package.address_code == local.address_code);
var package_required_truck =  (package.weight > 80 );

if( package_arrived && package_required_truck ){
     truck.sendAndCollect(package);
}

vs

code:

if( ( package.address_code == local.address_code) && (package.weight > 80 ) ){
     truck.sendAndCollect(package);
}


This post actually highlights one of the reasons I tend to use variable declarations even if it's just used once:

If you use the second example, you have no context for package.weight. why is that relevant? Why is it relevant that the package address matches the local address? For all we know, the addresses matching means the package never left. For all know, we always send trucks.

The former example gives context and explains the situation while simultaneously making the if statement easier to read. When you come to fix a bug later, you'll realize that address matching is to check arrivals and not departures and that trucks are only required for large items. That information might allow you to make a better decision about fixing that bug.

It's not just the if conditions that it helps clarify, it's your understanding of the whole system.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

IAmKale posted:

Does VueJS have a concept of a "service"? I'm trying to figure out how to initialize a singleton class to wrap an API and manage auth credentials and use it across multiple components and pages. If I just use a regular "import...from..." when I want to use the class of course it won't preserve state and I'll have to initialize it every time.

I'm also incorporating Vuex and it's not yet obvious how best to expose the API class to a store module so I can make async requests in an action. Any tips?

You can export the instance you want to work with, javascript will only really import anything one time so you always end up with the first instance you created in whatever module you're importing. In Vuejs I like to just augment the vue instance itself.

code:
import Vue from 'vue';

import socket from './socket';
import router from './router';
import store from './store';

import App from './App.vue';

Vue.prototype.$socket = socket;

new Vue({
    el: '#app',
    store,
    router,
    render: h => h(App)
});
Not sure if I'm not supposed to do that. But `socket` is my own websocket api instance thingy and in this way it's available throughout my app like store and router.

code:
    mounted () {
        this.$socket.send('my.endpoint', myParams, (error, result) => {
            // etc.
        });
    },
I'm not sure what you mean in your question about actions. They give you access to context so you can use `commit` to trigger mutations within your actions to update the store. You can also cheat and import your store instance at the top of the file then just use that directly.

What does javascript want from me! I've given it everything! My whole life!

Nolgthorn fucked around with this message at 14:40 on Mar 14, 2018

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I suppose an equally good if not less invasive way to do it, since prototype extensions are rightly frowned upon, is.

code:
import Vue from 'vue';

import socket from './socket';
import router from './router';
import store from './store';

import App from './App.vue';

const vue = new Vue({
    el: '#app',
    store,
    router,
    render: h => h(App)
});

vue.$socket = socket;
I think while writing that I was wondering why in beelzebub's name Vue needed to be an instance. Then I remembered. In the future when someone has this and 100 other Vue apps all running in the same tab, they probably wouldn't take kindly to my `$socket` instance being attached to the entire Vue prototype.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
Thanks for the ideas on how to augment a Vue instance with an API client, I can see that coming in handy if an app-wide store isn't available. Though I'd probably look into creating a proper plugin to add it as an global variable on this instead of faking it with a direct assignment.


Nolgthorn posted:

I'm not sure what you mean in your question about actions. They give you access to context so you can use `commit` to trigger mutations within your actions to update the store. You can also cheat and import your store instance at the top of the file then just use that directly.
The second part of my question was related to creating vue-router route guards. I wanted to be able to access the app's Vuex store from within methods that won't have access to this.$store (as they run prior to a component being rendered). Once I discovered the ability to import the store as-is with a regular import...from... statement as you mentioned I was able to write these no problem.

abraham linksys
Sep 6, 2010

:darksouls:
very open-ended question here: anyone using Vue + TypeScript? loving around with a personal project rewrite in Vue (really interested in the SSR stuff), but it seems like Vue+TS is spotty enough I'd maybe benefit by just dropping TypeScript. specifically, stuff like "can't type-check this.$store inside a component definition" seems like a no-go. if it were just a lot of any types I'd keep using TS just so I don't have to, like, set up a babel config and at least have type checking on a few things, but I'm getting straight-up errors when trying to write some of the code like in the SSR guide because the type defs don't take into account adding injecting and adding things to components (like the asyncData method)

setting up Vue+SSR has been pretty okay other than that. the worst part was that the SSR guide is awesome and detailed on setting up Webpack, how to architect your code, etc., but then doesn't tell you how to set up your dev server at all - I had to copy-paste a lot of stuff from the official example repo to create a dev server that watches and builds the multiple Webpack bundles you need.

also, I kinda just shoved the SSR server into my existing Node API server, which sorta works, but has a funny problem in dev: when I change API code on my server, it has to restart whole server to go into effect, and this requires the server to rebuild all the Webpack bundles in dev (since it's not cached between runs). this isn't a problem with the actual Vue codebase, which just triggers a Webpack rebuild and not a server restart, but means that I probably need to split my API and SSR servers. that actually might make it easier to treat the SSR server as a "client" to the API server, I guess?

in general I'm kinda worried about building out the API-client bit of this app and making sure it works on the client and server, but it looks like the trick is relatively simple:

- use a universal JS lib for making requests (axios seems like the most common choice)
- for authentication, use cookies to store an authentication token, so your SSR server has access to a client's token on request (as opposed to localStorage, which would only be visible from the browser)
- pass the authentication token from cookies into your app's store on both the server and client
- attach the token from the store to all API requests

honestly not that bad. the other thing I'm kind of bothered by is that I'm going to end up doing multiple HTTP requests for authenticated users - one to get the current user, one+ to get the rest of the data required by the page - and I feel like that's got some of the same overhead problems as doing multiple HTTP requests from the browser? maybe this is over-optimizing, though (as if SSR for a toy app isn't over-optimizing by its nature, though hey, at least now I'll have better <meta> tags for rendering Twitter cards or whatever)

abraham linksys fucked around with this message at 19:07 on Mar 14, 2018

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Nolgthorn posted:

code:
import Vue from 'vue';

import socket from './socket';
import router from './router';
import store from './store';

import App from './App.vue';

const vue = new Vue({
    el: '#app',
    store,
    router,
    render: h => h(App)
});

vue.$socket = socket;

Just wanted to update to mention the above code does not work and reading about building plugins the recommended way to implement is to extend the prototype as I did in the first try. :doh:

So. This basically takes me back to "why is Vue an instance."

Maybe future versions of Vue will have a way to do this more elegantly.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
My understanding of Vue + TypeScript is "it's not ready" however I'm certain there are people out there who would love more contributors on the topic.

Ape Fist
Feb 23, 2007

Nowadays, you can do anything that you want; anal, oral, fisting, but you need to be wearing gloves, condoms, protection.
dumbshit question but wouldn't just using npm to compile the TS down to JS work just fine in a vue app?

probably not.

I have literally 0 experience with Vue.



If Vue doesn't really support TS that kinda sucks. TS is such a vastly superior iteration of JS that it's mental. Having good TS support would also attract Angular2 devs to try it out and get familiar with it because working with Angular2 for long enough gets you really handy with the way TS does things.

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me
It's not that Vue doesn't support TS or it can't work with it, it's just the typing files supplied are a little rough. I've had no problems using it so far and am quite happy with how the two work together.

Check out vue-inject to get AngularJS like DI for services.

Check out vuex-typescript for getting strongly typed functions for your vuex store.

Check out vue-class-component for defining your components with decorators like in Angular.

Adbot
ADBOT LOVES YOU

Ape Fist
Feb 23, 2007

Nowadays, you can do anything that you want; anal, oral, fisting, but you need to be wearing gloves, condoms, protection.

Skandranon posted:

It's not that Vue doesn't support TS or it can't work with it, it's just the typing files supplied are a little rough. I've had no problems using it so far and am quite happy with how the two work together.

Check out vue-inject to get AngularJS like DI for services.

Check out vuex-typescript for getting strongly typed functions for your vuex store.

Check out vue-class-component for defining your components with decorators like in Angular.

I feel like at this point you could just use Angular. :anime:

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply