"Pew! Pew!" is a phonetic representation that native (American) English speakers make to simulate the sound and explosive nature of gunfire. Young boys typically made (still make) this sound when simulating gun battles, initially simulating firearms, and over time evolving to also represent science fiction weapons.
It's typically an approximation, not an exact representation, particularly with regard to gunfire, and some will often make the noise with more explosive affect, when trying to simulate certain types of gunfire.
As noted in one of the comments, this phonetic sound is also close to silenced gunfire.
Early movies and TV also popularized this sound for gunfire. Western movies, and TV action shows have used a variant of this sound for decades.
Science fiction TV and movie sound effects professionals adopted a similar, familiar, gunfire-like sound for many types of laser-like weapons. It's also ubiquitous in video games.
I really don't ever recall see the "Pew! Pew! in popular written works. It would be more common to see "Bang! Bang!" or a more colorful descriptive account of the weapon fire.
I believe the roots are simply that this sound is easy for English speakers to make and is universally understood as gunfire in a role play situation. Note that a commenter from India above described a similar-but-different sound used there that serves the same purpose.
Source: My cousins playing army with me in the 1970's and using this sound then. I'm sure the roots go way back before that.