Vue

Vue

Vue 3

Refs

  1. Composition API - An animated explanation
  2. Vue2 to Vue3 — What’s changed?
  3. Why vite ?
  4. A definitive guide to Vue 3 components
  5. ViteJS
  6. What is the difference between “vite” and “vite preview”?

Vue 3 VS Vue 2

Composition API vs Options API

Composition API vs Options API
Options API is function concerned.
Composition API is logic concerned.
For complex components, code of same logic may be scattered in props, data, methods, mounted, which makes it hard to maintain. So in Vue 3, Composition API is introduced, code of same logic is put together in setup.
See which to choose.

createApp vs vue instance

In Vue 2, we mount a App.vue instance to #app:

1
2
3
new Vue({
store, router, render: h => h(App)
}).$mount('#app')

In Vue 3, we createApp from a App.vue and mount to #app:

1
createApp(App).use(store).use(router).mount('#app')

Why use createApp over new Vue ?

In Vue 2, any directives created using Vue object will be usable by all application instances. This becomes a problem when our web app has multiple Vue application instances but we want to limit certain functionality to specific instances.

1
2
3
4
5
6
7
8
// The only way to create a directive in Vue 2
Vue.directive('directive', {
// ...
});

// Both of the application instances can access the directive
const appOne = new Vue(App1).mount('#app1');
const appTwo = new Vue(App2).mount('#app2');

Vue 3 solves this problem by creating directives on app instance instead of Vue object:

1
2
3
4
5
6
7
8
9
10
11
12
// Both of the application instances can access the directive
const appOne = Vue.createApp(App1);
appOne.directive('directive', {
// only availalble "appOne" instance */
});
appOne.mount('#app1');

const appTwo = Vue.createApp(App2);
appTwo.directive('directive', {
// only availalble to "appTwo"
});
appTwo.mount('#app2');

Vite

Vue 3’s scaffolding tool migrated from vue-cli to ‘create-vue’, which is based on vite and has a much faster building speed than webpack. See why vite is much faster

For more information about vite, check out my post named Vite on this blog.

Vue 3 features

Composition API

  • Difference with Options API already explained above.
  • Use <script setup> or <script>setup() to indicate Composition API. Difference between <script setup> and <script>setup() is that no return is required in <script setup> to pass objects to template.
  • A typical <script setup> SFC(Single File Component) goes here:
    script_setup_SFC

FAQ

ref() vs reactive()

  • reference:
    ref vs reactive in Vue 3
    Reactivity Core

  • Usage
    ref: Returns a deep reactive mutable object, point to inner value with .value. If an object assigned, reactive() is called. Use shallowRef() to avoid deep conversion.
    reactive: Returns a deep reactive proxy of the object.

  • Example

ref:

1
2
3
4
5
const count = ref(0)
console.log(count.value) // 0

count.value++
console.log(count.value) // 1

reactive:

1
2
const obj = reactive({ count: 0 })
obj.count++

Key Points

  • reactive() only takes objects, NOT JS primitives
  • ref() is calling reactive() behind the scenes, objects work for both
  • BUT, ref() has a .value property for reassigning, reactive() does not have this and therefore CANNOT be reassigned

Use

ref() when..

  • it’s a primitive
  • it’s an object you need to later reassign (like an array - more info here)

reactive() when..

  • it’s an object you don’t need to reassign, and you want to avoid the overhead of ref()

In Summary

ref() seems like the way to go since it supports all object types and allows reassigning with .value. ref() is a good place to start, but as you get used to the API, know that reactive() has less overhead, and you may find it better meets your needs.

ref() Use-Case

You’ll always use ref() for primitives, but ref() is good for objects that need to be reassigned, like an array.

1
2
3
4
5
6
7
setup() {
const blogPosts = ref([]);
return { blogPosts };
}
getBlogPosts() {
this.blogPosts.value = await fetchBlogPosts();
}

The above with reactive() would require reassigning a property instead of the whole object.

1
2
3
4
5
6
7
setup() {
const blog = reactive({ posts: [] });
return { blog };
}
getBlogPosts() {
this.blog.posts = await fetchBlogPosts();
}

reactive() Use-Case

A good use-case for reactive() is a group of primitives that belong together:

1
2
3
4
5
const person = reactive({
name: 'Albert',
age: 30,
isNinja: true,
});

the code above feels more logical than

1
2
3
const name = ref('Albert');
const age = ref(30);
const isNinja = ref(true);

If you’re still lost, this simple guide helped me: https://www.danvega.dev/blog/2020/02/12/vue3-ref-vs-reactive/

An argument for only ever using ref(): https://dev.to/ycmjason/thought-on-vue-3-composition-api-reactive-considered-harmful-j8c

The decision-making behind why reactive() and ref() exist as they do and other great information, the Vue Composition API RFC: https://vuejs.org/guide/extras/composition-api-faq.html#why-composition-api

ref unwrap

reference:
Reactivity Core

Vue Cli Plugins and Presets

reference: Plugins and Presets

  • What are plugins ?
    Plugins modify the internal webpack configuration and inject commands to vue-cli-service.

Most of the features listed during the project creation process are implemented as plugins.

If you inspect a newly created project’s package.json, you will find dependencies that start with @vue/cli-plugin-. These are plugins.

  • Add a plugin to an existing project
    Use vue add [plugin name] to add a plugin to an existing project.
    For example, use vue add eslint to add eslint linter to the project.

  • What is a Vue Cli preset ?
    A JSON object that contains pre-defined options and plugins for creating a new project.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"useConfigFiles": true,
"cssPreprocessor": "sass",
"plugins": {
"@vue/cli-plugin-babel": {},
"@vue/cli-plugin-eslint": {
"config": "airbnb",
"lintOn": ["save", "commit"]
},
"@vue/cli-plugin-router": {},
"@vue/cli-plugin-vuex": {}
}
}

How to get query string in vue 3 ?

  • In vue 2, we got this.$route.query to get query string.
  • In vue 3, first import { useRoute } from 'vue-router', then useRoute().query to get query string.

Useful commands

  • Use vue ui to start a ui interface inside a project created by vue-cli.
  • Use vue add typescript to add typescript plugin to a vue-cli project and transform it to a typescript project.

Vue Component Communication

Ref

Component communication has three forms:

  1. Parent -> Child
  2. Child -> Parent
  3. Global
  • Parent send messages to child through props. Any change to prop is reflected immediately. Prop is immutable in child so vice versa not viable. This is a one-way communication.

Others

Add global property to Vue instance

1
2
3
4
// Vue 2
Vue.prototype.$http = axios.create({ /* ... */ })
// Vue 3
app.config.globalProperties.$http = axios.create({ /* ... */ })
Author

Chendongtian

Posted on

2022-06-27

Updated on

2022-10-29

Licensed under

Comments