A few months ago, UVU launched a lightweight VUE. I have read it before, but after I read it briefly and clicked a star, I stopped reading it. A few days ago, I had to write a small tool for data processing for operation, which was only one page. Petite Vue is a 6KB incremental enhancement alternative to VUE.

Did not think of a few short months, this star quantity Dally go up, especially big not kui is front end giant engine HHH

introduce

Official summary: Petite-Vue is an alternative release to VUE optimized for progressive enhancement. It provides the same template syntax and reactive thinking model as standard Vue. However, it is specifically optimized for “spreading out” a small number of interactions over existing HTML pages rendered by the server framework.

In other words, Petite-Vue, while providing the basic functionality of VUE, is also a lightweight, simple application microframework that ensures a great experience for developers.

  • Only ~ 6 KB
  • Vue compatible template syntax
  • DOM based, in place mutation
  • By driving @vue/reactivity

usage

1. Super simple CDN loading and use

<script src="https://unpkg.com/petite-vue" defer init></script>

<! -- anywhere on the page -->
<div v-scope="{ count: 0 }">
    { { count }}
    <button @click="count++">inc</button>
</div>
Copy the code
  • V-scope marks the page, which is rendered with Petite-Vue and also declares data and methods.
  • The script defer attribute causes the script to execute after the HTML content has been parsed.
  • Script’s init property tells Petite-Vue to automatically query and initialize all elements on the page’s V-scope.
    • So init here is essentially the same thingPetiteVue.createApp().mount()Concise writing;
    • Reading the source code,
      • const s = document.currentScript;
      • if (s && s.hasAttribute(‘init’)) {
      • createApp().mount();
      • }
    • If you don’t want automatic initialization, remove the init attribute and, in the Script tag, addPetiteVue.createApp().mount().
    • Of course, you can also build with the ES module if the target browser supports module references
<script type="module">
    import { createApp } from 'https://unpkg.com/petite-vue?module';
    createApp().mount();
</script>
Copy the code

Important: At the time of development, CDN addresses can behttps://unpkg.com/petite-vueThis brief, but for production use, should use the fully parsed CDN URL.

Such as:https://unpkg.com/[email protected]/dist/petite-vue.iife.jsorhttps://unpkg.com/[email protected]/dist/petite-vue.es.jsIn addition to avoiding parsing and redirecting text (when referenced by the ES module), you can also avoid project surprises caused by different versions

Use terminal commands to quickly and easily download code locally

The curl unpkg.com/petite-vue@… – the output [email protected]

2. Root Scope: Sets the Root Scope of the data expression

CreateApp (), which receives a data object as a variable in the root scope for use in the template.

<script type="module">
    import { createApp } from 'https://unpkg.com/petite-vue?module';

    createApp({
        count: 0.// getters
        get plusOne() {
            return this.count + 1;
        },
        increment() {
            this.count++;
        },
    }).mount();
</script>

<! -- v-scope value can be omitted -->
<div v-scope>
    <p>{{ count }}</p>
    <p>{{ plusOne }}</p>
    <button @click="increment">increment</button>
</div>
Copy the code

This allows you to use the count variable, increment method in the template,

3. Mount () : Mount elements

Petite-vue applies to the entire page when mount() is not passed in, but only to the mount element and the elements within it when mount() is passed in.

This also means that we can mount multiple Petite-Vue applications on the same page, each with its own range of root variables.

createApp({
    // root scope for app one
}).mount('#app1');

createApp({
    // root scope for app two
}).mount('#app2');
Copy the code

4. Life cycle

In Petite-Vue, you can listen for mount and unload events for each element.

As of V0.4.0, binding life cycle events need to be prefixed with @vue:.

<!-- v0.4.0 以下 -->
<div v-if="show" @mounted="console.log('mounted on: ', $el)" @unmounted="console.log('unmounted: ', $el)">
    some node
</div>

<! -- v0.4.0 or above -->
<div v-if="show" @vue:mounted="console.log('mounted on: ', $el)" @vue:unmounted="console.log('unmounted: ', $el)">
    some node
</div>
Copy the code

5. The component

Small as the sparrow is, it has all the five organs. What are the components of Mini-Vue?

There are two ways to create a component: a function component with pure data and a function component with a template

With components, you need to use v-scope to call functions within elements.

Function component

<script type="module">
    import { createApp } from 'https://unpkg.com/petite-vue?module';

    function Counter(props) {
        return {
            count: props.initialCount,
            inc() {
                this.count++;
            },
            mounted() {
                console.log(`I'm mounted! `); }}; } createApp({ Counter, }).mount();</script>

<div v-scope="Counter({ initialCount: 1 })" @vue:mounted="mounted">
    <p>{{ count }}</p>
    <button @click="inc">increment</button>
</div>

<div v-scope="Counter({ initialCount: 2 })">
    <p>{{ count }}</p>
    <button @click="inc">increment</button>
</div>
Copy the code

Function components with templates

If a template is also required, there is one more field than the function component to declare the template: $template, which can be either a template string or an ID selector for the

<script type="module">
    import { createApp } from 'https://unpkg.com/petite-vue?module';

    function Counter(props) {
        return {
            $template: '#counter-template'.// $template: `
            // My count is {{count}}
            // 
            / / `,
            count: props.initialCount,
            inc() {
                this.count++; }}; } createApp({ Counter, }).mount();</script>

<template id="counter-template">
    My count is {{ count }}
    <button @click="inc">++</button>
</template>

<! -- reuse it -->
<div v-scope="Counter({ initialCount: 1 })"></div>
<div v-scope="Counter({ initialCount: 2 })"></div>
Copy the code

6. Global status management

Yes, even a simple Mini-Vue can have global state management. Vue3’s Reactive API is used for global state management.

<script type="module">
    import { createApp, reactive } from 'https://unpkg.com/petite-vue?module';

    const store = reactive({
        count: 0.inc() {
            this.count++; }});// manipulate it here
    store.inc();

    createApp({
        // share it with app scopes
        store,
    }).mount();
</script>

<div v-scope="{ localCount: 0 }">
    <p>Global {{ store.count }}</p>
    <button @click="store.inc">increment</button>

    <p>Local {{ localCount }}</p>
    <button @click="localCount++">increment</button>
</div>
Copy the code

7. The instructions

Built-in commands

  • v-model
  • v- if / else / else-if
  • v-for
  • v-show
  • V-on (alias: @)
  • V-bind (alias: 🙂
  • v- html / text / pre
  • v-once
  • V-cloak (used to cloak CSS when unrendered)

Custom instruction

Petite-vue’s custom directives are a little different from Vue’s.

  • Instruction declaration: a function,const myDirective = (ctx) => {};
    • CTX is an object that hasel, arg, get, effectAnd other attributes, specific can beReference documentationorRead the source code
    • The return function is fired when an instruction is unloaded.
  • Registration Instruction:createApp().directive('dir-name', dirFn).mount()

Implementation of V-HTML instructions

const html = ({ el, get, effect }) = > {
    // effect, executed after every get() change
    effect(() = > {
        el.innerHTML = get();
    });
};
Copy the code

8. Customize templates

This can be done by adding the attribute $delimiters: [‘${‘, ‘}’] to the createApp configuration item, which is usually useful when used with server-side template languages.

practice

Here wrote a small tool, is used for operation to modify a page of data, support data import and export, new editor.

Conclusion & Final

In general, the petite-Vue project is suitable for simple page building, without the use of vue, React and other large front-end frameworks.

Having the experience of vUE development without adding to the complexity of the project is a perfect experience.

Finally, during the Spring Festival holiday, you can use this small project to see the source code, code ideas, etc., really sweet HHH, after the year, I will write a blog about the petite-Vue source code reading series