Luna  Mosciski

Luna Mosciski

1602255420

The Ultimate Nuxt.js Cheat Sheet

In this article, we will looking into some of the Nuxt essential and how we can use them in our application. It’s advisable to understand the basic of Vuejs before moving into Nuxt js. Before we start with our Nuxt Js Cheat Sheet, lets learn about Nuxt.

Nuxt.js is a free and open source web application framework based on Vue.js, Node.js, Webpack and Babel.js. The framework is advertised as a “meta-framework for universal applications”

Lets look at some of the essentials in Nuxt:

Installation of Nuxt Js

You can setup a new Nuxt projectby using the Nuxt toolkit of by setting it up from scratch.

  • Setting up using the Nuxt toolkit:
npx create-nuxt-app <name of project>
    cd <name of project>
    npm install #installs the project default dependencies
    npm run dev ## serves the application on a local port
  • Setting up from scratch:
Create a `package.json` file and add this code:
    {
    "name": "stater app",
    "scripts": {
      "dev": "nuxt"
    }
    }

After doing this, run npm install --save nuxt to store the Nuxt dependency and then run npm run dev to serve the application.

#web-development #nuxtjs #vuejs #nextjs #vue

What is GEEK

Buddha Community

The Ultimate Nuxt.js Cheat Sheet

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Lupe  Connelly

Lupe Connelly

1626953460

Create Dating App (Vue Js Capacitor) Using Nuxt Js, Laravel, Socket IO - #1

Give me a design and coding challenge !

Day for #100DaysOfCode Challenge

Sources :
Trello : https://trello.com/invite/b/kGXI8zlV/d4a415ab005f801d82939d886232334e/100daysofcode
Figma https://figma.com/@kewcoder
Github https://github.com/kewcoder

#laravel #nuxt #nuxt js #socket io #vue js

Lupe  Connelly

Lupe Connelly

1626960900

Create Dating App (Vue Js Capacitor) Using Nuxt Js, Laravel, Socket IO - #3

Give me a design and coding challenge !

Day for #100DaysOfCode Challenge

Sources :
Trello : https://trello.com/invite/b/kGXI8zlV/d4a415ab005f801d82939d886232334e/100daysofcode
Figma https://figma.com/@kewcoder
Github https://github.com/kewcoder

#vue #vue js #nuxt js #nuxt #laravel #socket io

Taylor Adina

Taylor Adina

1558663581

Nuxt.js cheat sheet

Nuxt.js is a higher-level framework that builds on top of Vue. It simplifies the development of universal or single page Vue apps. Nuxt.js is not a server side framework. It runs on the servers. It renders the first page and after the first page is renderd, the Vue.js app takes over.

Nuxt.js is here to make your life easy, it’s also here to make the Vue.js development process even nicer than it already is. But with all its good aspects, it has quirks that will have you click on every single link on Google.

This article is here to avoid these situations, it’ll cover some normal use-cases and some edge-cases with quick and easy code snippets. It won’t go into extreme detail on these matters, but will give you the documentation necessary to do so in case you want to.

Note: You’ll need a good grasp of Vue.js concepts to take full advantage of this article !
Before we get into anything concrete, let me explain what Nuxt.js is.

What’s Nuxt.js?

Nuxt.js is a framework based on Vue.js that allows you to build fully fledged server-rendered applications.

It comes out of the box with loads of useful packages:

  • 💻 Vue
  • ↩️ Vue Router (for easy routing)
  • 💾 Vuex (for easy state management)
  • 🏎 Vue Server Renderer (for server-side rendering out of the box)
  • 🕵️‍♂️ Vue meta (for SEO)

Here’s a list of what we’ll cover (feel free to come back here if you’re searching for something specific):

General

  • Creating a Nuxt.js project
  • Testing with Nuxt.js

Routing

  • Creating a new route
  • Creating dynamic routes
  • Navigating to a route in a component template
  • Navigating to a route programatically

State management

  • Creating a new store module
  • Updating a store before rendering a component

SEO

Miscellaneous

  • Displaying a fixed component throughout your app
  • Changing a project’s router base
  • Handling internationalization (i18n)
  • Importing a font to your project

If you have any other requests or want to add anything new, please feel free to hit me up on Twitter @christo_kade !

Creating a Nuxt.js project

yarn create nuxt-app <project-name>

Which will prompt you to answer some questions, including:

  • Choose between integrated server-side frameworks (None by default, Express, Koa etc.)
  • Choose features to install (PWA Support, Linter / Formatter, Prettier, Axios)
  • Choose your favorite UI framework (None by default, Bootstrap, Vuetify, Bulma etc.)
  • Choose your favorite testing framework (None, Jest, AVA)
  • The Nuxt mode you want (Universal or SPA, more information)

Once done and your dependencies are installed:

$ cd <project-name>
$ yarn dev

Documentation

Testing with Nuxt.js

The majority of your testing syntax will depend on the testing framework chosen during the project’s creation.

Out of the box, Nuxt uses the @vue/test-utils package to render your components thanks to multiple methods such as mount(), shallowMount()and render(). You’ll then be able to test that specific values have been displayed, that specific methods were called etc.

Nuxt will also make sure to set everything up for you, all you’ll have to do is create your *.spec.js or *.test.js files and run the yarn test command.

Here’s a classic (and brief) example of unit testing for a Vue component in a Nuxt project:

import { shallowMount } from "@vue/test-utils"
import cmp from "~/components/navbar/navbar"

// Mocking an icon displayed in my navbar
jest.mock("~/static/icons/svg/icon-menu.svg", () => "")

describe("Navbar component", () => {

  // We shallow mount the component while mocking some internal elements
  // Most of the time, you'll have to mock context objects such as $store or $route in order to render your component whithout any errors
  const wrapper = shallowMount(cmp, {
    // Stubbing nuxt-links in the navbar
    stubs: ["nuxt-link"],
    mocks: {
      "nuxt-Link": true,
      // Mocking the $store context object
      $store: {
        state: {
          locale: "en",
        },
      },
      // Mocking the $route context object
      $route: {
        path: "mockedPath",
      },
    },    
  })

  it("Snapshot testing", () => {
    expect(wrapper.html()).toMatchSnapshot()
  })

  describe("Components validation", () => {
    it("should return a valid component", () => {
      expect(wrapper.is(cmp)).toBe(true)
    })
  })

  describe("Content validation", () => {
    it("should render the link's name", () => {
      expect(wrapper.html()).toContain("About")
    })

    // ...
  })
})

Documentation

Creating a new route

In the /pages folder, create a file, its name will be the name of the route.

So for example:

// /pages/about.vue

<template>
  <main>
    <h1>About page</h1>
  <main/>
</template>

<script>
export default {}
</script>

<style></style>

Navigating to localhost:3000/about will display this component’s content

Documentation

Creating dynamic routes

In the /pages folder, create a directory and a file prefixed by an underscore.

For example, the following file tree:

pages/
--| users/
-----| _id.vue
--| index.vue

Will automatically generate the following router inside the .nuxt folder whenever you build your project:

router: {
  routes: [
    {
      name: 'index',
      path: '/',
      component: 'pages/index.vue'
    },
    {
      name: 'users-id',
      path: '/users/:id?',
      component: 'pages/users/_id.vue'
    },
  ]
}

You can now navigate to /users/:id, with id being whatever value you need it to be.

To retrieve this value in your _id.vue component, just do the following:

// $route is a Nuxt context object, more info: https://nuxtjs.org/api/context
const { id } = this.$route.params

Documentation, including nested routes and dynamic nested routes.

Navigating to a route in a component template

Inside of any of your components:

// /components/example.vue

// Clicking on this nuxt-link will navigate to the /pages/about.vue component
// nuxt-link renders an <a> tag in your HTML
<template>
  <section>    
    <nuxt-link to="/about">
      About
    </nuxt-link>
  </section>
</template>

// ...

Documentation

Navigating to a route programatically

// Will add a history entry to the stack
this.$router.push({
  path: '/about'
})

// Will not
this.$router.replace({
  path: '/about'
})

// Goes back one record
this.$router.go(-1)

Creating a new store module

In the /store folder, each file is a Vuex module.

// /store/todos.js
export const state = () => ({
  list: []
})

export const mutations = {
  add(state, text) {
    state.list.push({
      text: text,
      done: false
    })
  },
  remove(state, { todo }) {
    state.list.splice(state.list.indexOf(todo), 1)
  },
  toggle(state, todo) {
    todo.done = !todo.done
  }
}

Each module’s mutations, actions & states are now available using the context object $store:

// /components/todo.vue
<template>
  <ul>
    <li v-for="todo in todos">
      <input type="checkbox" :checked="todo.done" @change="toggle(todo)">
      <span>{{ todo.text }}</span>
    </li>
    <li><input placeholder="What needs to be done?" @keyup.enter="addTodo"></li>
  </ul>
</template>

<script>
import { mapMutations } from 'vuex'

export default {
  computed: {
    todos () {
      return this.$store.state.todos.list // highlight-line
    }
  },
  methods: {
    addTodo (e) {
      this.$store.commit('todos/add', e.target.value) // highlight-line
      e.target.value = ''
    },
    ...mapMutations({ // highlight-line
      toggle: 'todos/toggle' // highlight-line
    }) // highlight-line
  }
}
</script>

Documentation

Updating a store before rendering a component

Sometimes you need to fill up a given state variable before rendering a component, here’s how:

// In any component

export default {
  // Called before rendering the component
  fetch ({ store, params }) {
    return axios.get('https://dog.ceo/api/breeds/image/random')
    .then((res) => {
      store.commit('setDog', res.data.message)
    })
  }
}

Warning: You don’t have access of the component instance through this inside fetch because it is called before initiating the component (read more).
Documentation

Changing a page’s head properties dynamically

For SEO purposes, defining the page’s title, description keywords etc. can be useful. Here’s how you can do it programmatically:

// In any component
export default {
  head: {
    title: 'Page title',
    meta: [
      { 
        hid: 'description', name: 'description', 
        content: 'Page description' 
      }
    ],
    // ...
  }
}

Info: To avoid duplicated meta tags when used in child component, set up an unique identifier with the hid key for your meta elements (read more).
Documentation

SSR for dynamic routes

When running nuxt generate, the HTML file for your dynamic routes won’t be generated by default.

For example, if you have an about.vue page and a _id.vue one, when running nuxt generate, the resulting dist folder will contain /about/index.html but won’t generate anything for your dynamic _id.vue.

This can lead to your dynamic routes to be missed by crawlers, and therefore not referenced by search engines !

Here’s how you can generate them automacially:

// nuxt.config.js

module.exports = {
  // ...

  // dynamicRoutes could be a JSON file containing your dynamic routes
  // or could be retrieved automatically based on the content of your /pages folder
  generate: {
    routes: () => {
      return dynamicRoutes.map(route => `/articles/${route}`)
    },
  },

  // ...
}

nuxt generate will now generate the HTML file for each dynamic route returned by the generate property.

Documentation

Displaying a fixed component throughout your app

Sometimes you need to add a navbar or a footer that will be displayed no matter the current route.

There’s a /layout folder that contains default.vue by default. This layout holds the <nuxt/> component that takes care of rendering the content of each one of your pages (see Creating a new route).

Simply modify that component to fit your needs, for example:

<template>
  <div>
    <navbar/>
    <nuxt/>
    <footer/>
  </div>
</template>

<script>
import navbar from "~/components/navbar/navbar"
import footer from "~/components/footer/footer"

export default {
  components: {
    cmpNavbar,    
    cmpFooter,
  },  
}
</script>

Documentation

Changing a project’s router base

In some cases, when for example you’re deploying your project on Github Pages under username/my-project, you’ll need to change the project’s router base so that your assets are displayed correctly.

// nuxt.config.js

// Will change the router base to /my-project/ when DEPLOY_ENV equals GH_PAGES
const routerBase = process.env.DEPLOY_ENV === "GH_PAGES"
  ? {
    router: {
      base: "/my-project/",
    },
  }
  : {
    router: {
      base: "/",
    },
  }

module.exports = {  
  // ...
  routerBase,
  // ...
}

And don’t forget to change your package.json so that nuxt.config.jsknows when you’re building or generating for Github Pages.

// package.json

"scripts": {
  "build:gh-pages": "DEPLOY_ENV=GH_PAGES nuxt build",
  "generate:gh-pages": "DEPLOY_ENV=GH_PAGES nuxt generate"
},

Handling internationalization (i18n)

Start by running yarn add vue-i18n

Create the following file:

// /plugins/i18n.js

import Vue from "vue"
import VueI18n from "vue-i18n"

Vue.use(VueI18n)

export default ({ app, store }) => {

  // Set i18n instance on app
  // This way we can use it globally in our components
  app.i18n = new VueI18n({
    locale: store.state.locale,
    fallbackLocale: "fr",
    messages: {
      // Add the supported languages here AND their associated content files
      en: require("~/static/json/data-en.json"),
      fr: require("~/static/json/data-fr.json"),      
    },
  })
}

And add the following line in your nuxt.config.js to inform it we’re using that plugin:

module.exports = {
  // ...
  plugins: ["~/plugins/i18n.js"],
  // ...
}

In this example, the current locale is based on my store’s content, which looks like so:

export const state = () => ({
  locales: ["en", "fr"],
  locale: "fr",
})

export const mutations = {
  setLanguage(state, locale) {
    if (state.locales.indexOf(locale) !== -1) {
      state.locale = locale
    }
  },
}

So whenever we call setLanguage, the locale is automatically updated and the correct JSON file is loaded ! ✨

Your file contents are now available throughout your application like so:

// Here we access the 'users' array in our JSON file
this.$t("users")

Documentation

Importing a font to your project

// nuxt.config.js

module.exports = {
  /*
   ** Headers of the page
   */
  head: {    
    // ...
    link: [
      {
        rel: "stylesheet",
        href: "https://fonts.googleapis.com/css?family=Lato",
      },
    ],
  },

  // ...
}

Wrapping up

Alright, I believe that’s enough for one article. I’ve covered lots of use-cases which hopefully will be useful to some of you.

#nuxt-js #vue-js

Hire Dedicated Node.js Developers - Hire Node.js Developers

If you look at the backend technology used by today’s most popular apps there is one thing you would find common among them and that is the use of NodeJS Framework. Yes, the NodeJS framework is that effective and successful.

If you wish to have a strong backend for efficient app performance then have NodeJS at the backend.

WebClues Infotech offers different levels of experienced and expert professionals for your app development needs. So hire a dedicated NodeJS developer from WebClues Infotech with your experience requirement and expertise.

So what are you waiting for? Get your app developed with strong performance parameters from WebClues Infotech

For inquiry click here: https://www.webcluesinfotech.com/hire-nodejs-developer/

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated node.js developers #hire node.js developers #hire top dedicated node.js developers #hire node.js developers in usa & india #hire node js development company #hire the best node.js developers & programmers