Vue 3 has not been officially released yet, but the maintainers have released beta versions for us punters to try and provide feedback on.

If you’re wondering what the key features and main changes of Vue 3 are, I’ll highlight them in this article by walking you through the creation of a simple app using Vue 3 beta 9.

I’m going to cover as much new stuff as I can including fragments, teleport, the Composition API, and several more obscure changes. I’ll do my best to explain the rationale for the feature or change as well.


What we’ll build

We’re going to build a simple app with a modal window feature. I chose this because it conveniently allows me to showcase a number of Vue 3 changes.

Here’s what the app looks like in it’s opened and closed states so you can picture in your mind what we’re working on:

Vue 3 app modal

Vue 3 installation and setup

Rather than installing Vue 3 directly, let’s clone the project vue-next-webpack-preview which will give us a minimal Webpack setup including Vue 3.

$ git clone https://github.com/vuejs/vue-next-webpack-preview.git vue3-experiment
$ cd vue3-experiment
$ npm i

Once that’s cloned and the NPM modules are installed, all we need to do is remove the boilerplate files and create a fresh main.js file so we can create our Vue 3 app from scratch.

$ rm -rf src/*
$ touch src/main.js

Now we’ll run the dev server:

$ npm run dev

Creating a new Vue 3 app

Straight off the bat, the way we bootstrap a new Vue app has changed. Rather than using new Vue(), we now need to import the new createApp method.

We then call this method, passing our Vue instance definition object, and assign the return object to a variable app.

Next, we’ll call the mount method on app and pass a CSS selector indicating our mount element, just like we did with the $mount instance method in Vue 2.

src/main.js

import { createApp } from "vue";

const app = createApp({
  // root instance definition
});

app.mount("#app");

Reason for change

With the old API, any global configuration we added (plugins, mixins, prototype properties etc) would permanently mutate global state. For example:

src/main.js

// Affects both instances
Vue.mixin({ ... })

const app1 = new Vue({ el: '#app-1' })
const app2 = new Vue({ el: '#app-2' })

This really shows up as an issue in unit testing, as it makes it tricky to ensure that each test is isolated from the last.

Under the new API, calling createApp returns a fresh app instance that will not be polluted by any global configuration applied to other instances.

Learn more: Global API change RFC.

#vue.js #components #composition api #design patterns #vue 3 #vue

Vue 3 Tutorial (for Vue 2 Users)
7.95 GEEK