preface

Before introducing the new version of Strve.js! Let’s take a look at two recent sharing by You Yuxi.


  1. How do you balance between being an open source when you still have a day job?

Maybe I’m luckier! Because in the US people are more concerned about work balance, like Google is more comfortable. We were young when we started, and we worked overtime occasionally, but in general, at Google, you can leave whenever you want. So it will be more difficult in China, and the business pressure will be big. So if you really feel more business pressure, you’re busy. Then I would suggest maybe not pushing yourself, if you really feel too tired, don’t push yourself. In fact, the open source itself is to say that everyone does open source in fact, there is a stage, when you first have an idea to make it, at the beginning, it is a state of happiness, it is to develop an idea from zero to that kind of pleasure, it is a technical personnel have this idea to create something. But open source in another process has been completed immediately into a, is from 90% to 100% of this process is very difficult, you will find a toy can make use of things you need to invest a lot, when you can do it really, really someone with, these people will continue to give you require. That is to say, alas! I have to respond to these people’s expectations, which is another psychological pressure. In fact, a lot of times, people are attracted to the thrill of creating something when they start doing open source. Not realizing that you’re going to have a lot of commits. My advice to a lot of people who want to do open source is to figure out what you want to do when you do open source. If you just want to write a library, it’s cool, but I don’t want to do it later and it costs me a lot of energy to maintain it, that’s fine. But if you want to do a project that’s going to be big and good and compete with React, it’s going to take a lot of investment. If your job is inherently busy, chances are you won’t be able to do it. So really, figure out what you want! If you are not really qualified, if you really work hard, I am 996, I also want to do open source, then you have to be prepared. I had a period of time to put myself into the 996 state, is after work to do Vue, in fact, such mental pressure is quite big. It’s probably easy for me to stand up now, but I’d still prefer a little balance.

Video link

2. What do you consider when designing a framework like Vue?

In fact, the consideration is that, first of all, this is quite large, of course, this consideration is not fully thought out at the beginning, Vue is also from a small project slowly developed. So what we’re saying is that you have a position on your framework, and Vue’s position is that we make sure it’s newbie friendly and easy to use. This is a positioning, some framework said, I am not designed for beginners, I will not consider this problem. It’s not good or bad, it’s just a design decision, I’m just going to be novices friendly with the framework, or I’m going to pay some price in other cases, like one of my API designs being hard to understand. But there are times when you go too far in trying to be newbie friendly, and you may be limited to high-end or performance-driven scenarios, so you have to make trade-offs. And on the other hand, there are frameworks that I don’t think about for novice users, I think about theoretical elegance, like a functional framework for a niche, which might be a very elegant, perfect model for some papers. But, if you’re a beginner, you might not understand what I’m doing. It’s a trade-off, right? So, the first thing to know is where your framework is positioned. And with that in mind, you also have to think about the fact that you’re going to find engineering problems later on. Trade-offs are everywhere. If you have an API, for example, you can choose to make the design more elegant, but that makes it hard to optimize in some places. In turn, IN my pursuit of extreme performance, I might design the API a little bit worse. Then there are the needs of the community, and the decisions you make may not be what the community wants. You need to talk to the community, and open up the discussion process. When Vue makes some big changes, it’s more about throwing an idea out there for the community to discuss. It becomes more of a co-design process than it is in the early days, where you just don’t have to think about so many users, you slap your head and you build it. So, the early stage and the late stage is completely different from the process you designed.

Video link


As you can see, UVU also gives good advice on open source frameworks. I was actually going to write strve.js, just to see if I could develop a library or framework that wasn’t too bad. Well, it worked out, too. Here are some thoughts from developing Strve.js on my own.

From September 2021, I wanted to develop a library myself to improve my capabilities. Fortunately, it was developed in the year before, and the ecology was also preliminary built. The ecosystem mentioned here includes the Create Strve App, Strve Router, and other tools that aid strve.js development.

To be honest, it’s a tough time, so this is a gift for myself this year.

I developed Strve.js initially because I had been exposed to JSX syntax, an intuitive and cool JSX syntax that allows you to write HTML tags in JS, so I wanted to develop a library similar to JSX syntax. JSX syntax is easy to implement with Babel. However, I felt it was not perfect and had to solve some problems like modifying the data and updating the view. Stay up for a few nights, there is no perfect solution. In the end, the plan was abandoned.

I was thinking, if I only want to write HTML tags in JS, then using the TEMPLATE string in JS has the ability to write HTML tags in the string, why not change the idea, to study the template string to write HTML tags in this more convenient and direct scheme? I started with the basics, writing a string, and then figuring out how to mount the string into the page. Use the React and Vue frameworks to specify a mount element on the page. This is an easy way to develop HTML within a template string, but it comes with the added disadvantage of not being able to convert data to pages, which in a more technical sense is data-driven pages. In addition, the DOM elements should be modified as little as possible after the page is updated to reduce the performance impact caused by rearrangement. This has gone from simply writing HTML in JS to the next level, how to implement an MVVM framework.

MVVM frameworks include Vue, React and Angular. If you want to design an MVVM framework, you can use their ideas. First of all, I like the progressive design idea of Vue very much. As long as you are a front-end novice, you can immediately get started, which is very worth learning from. In addition, it borrows the idea of “All in JS” in the React framework and asynchronously updating data. Finally, both frameworks use the virtual DOM to improve performance, so we can also introduce the virtual DOM mechanism.

Before, I heard several Chinese sharing sessions by You. When it comes to the topic of frame, the design of frame is a constant choice. It’s going to be a lot more complicated, and I’ve just outlined it briefly. I didn’t know at the time if it was going to work out the way I wanted it to. The first month or so was very painful and almost closed. The main challenge is how to convert template strings into virtual DOM structures with minimal code. Then the transformed virtual DOM is Diff algorithm to update DOM more effectively.

In the end, the hard work paid off and I finally finished strve.js. This small library is not really a framework. The original intention of the design is also said that I want to practice, to see if they can develop at least not very bad library or framework.

In December 2021, I released the first version, 1.2.2, which was relatively humble. However, the surrounding ecology has been preliminarily established. After the launch, I tried it out for myself and tried out a few small projects myself. Like everybody can do TodoList. How can I put it? As far as I’m concerned, it’s ok. Easy to use, most of the use of native JavaScript capabilities, so as long as you are familiar with JavaScript friends can use, and use declarative API to operate on some DOM, without the JQuery imperative API to take the DOM is dry. And in line with the MVVM framework ideas, easier to develop projects.

I agree with what Utah said, that it’s really hard to go from 90% to 100%, and you find that it takes a lot of investment to make a toy into something that actually works. I am thinking that since I have decided to develop a library, although it is not as good as Vue and React frameworks, why not just develop and maintain a project? So, I have to continue to optimize maintenance. In January 2022, I decided to optimize some of the code to make Strve.js better. Frame design as Utah university says you will find a concrete engineering problem later. Trade-offs are everywhere. I felt worse during this period than I did when I first started strve.js, because it’s hard to make something better. Finally, I realized what UVU said, and I think this is also a growth, at least WHEN I use Vue, I will not simply use its API. After a month of research and various tests, the second version 2.1.0 was released, followed by 2.0.0. I think that was a breakthrough, and I did it.

So, finally, I would like to tell some friends who do open source, in fact, do not think so complicated, do every step is ok.

[email protected]

Source code address:

Github.com/maomincodin…

2.0.0 (2022-01-23)

  • Inserting data into the head of the linked list requires binding the useFkey field to avoid repeated DOM node rendering.

  • Hide the “DOM” node event method after rendering

  • Bind Style Style (object);

  • Bind attributes using ${} symbol binding;

  • HTML template string highlighting (comment-ptagged -templates is required for the VSCode editor);

  • Support parent and child components to transmit values to each other;

  • Bootstrap5, Tailwindcss UI framework;

2.1.0 (2022-01-25)

  • Fixed DOM property assignment problem;
  • Improve string conversion to virtual DOM logic;

New Document Update

Chinese document address:

Maomincoding. Making. IO/strvejs – doc…

Update the content

  • Overall UI optimization;
  • The sidebar collapses by default;
  • Code theme optimization;
  • Search function optimization;
  • Add theme switch (day/night);
  • Add support UI framework menu items;
  • Add the update log menu item;
  • Update API usage details;

Preview effect drawing

Combat the first Strve project

The next project we are going to do is TodoList, I believe you have done it, it is also very practical. We do not pay attention to the style here, mainly to achieve simple add, delete and change the function.

Here’s the entire code, about 51 lines.

Here is what the page looks like.

Let’s run down the score!

The document”

introduce

Strve.js, pronounced/STR ‘vi/, is a concatenation of a String and a View. Strve.js is a JS library that can convert strings into views. The strings here refer to template strings, so you only need to develop the view in JavaScript. The view here refers to the HTML page we normally write, which is the view layer.

Not only is strve.js easy to get started with, but it also allows for the flexibility of unpacking different blocks of code. Developing views using template strings takes advantage of the power of native JavaScript, which allows you to separate blocks of code more flexibly, and you only focus on JavaScript files.

Strve.js is another lightweight MVVM framework. You only need to care about the data and how to manipulate it, leaving the rest to Strve.js. Strve.js first converts the template string into a virtual DOM, and then performs a Diff algorithm to update the real DOM by comparing the two states. This is what many frameworks use to improve browser performance, but strve.js is much lighter.

If you want to get started with the project, here’s how to install it.

The installation

CDN

If you use native ES Modules.

<script type="module">
  import { Strve, render} from 'https://cdn.jsdelivr.net/npm/strvejs/dist/strve.esm.min.js';
</script>
Copy the code

NPM

npm i strvejs
Copy the code

Command line tool

create-strve-app

A set of command line tools to quickly build strve.js projects. The Create Strve App goes one step further than the earlier scaffolding, Create Strve, by quickly creating Strve projects directly from commands. The Create Strve App is built with Vite, a new front-end build tool that significantly improves the front-end development experience.

npm

npm init strve-app@latest
Copy the code

yarn

yarn create strve-app
Copy the code

pnpm

pnpm create strve-app
Copy the code
create-strve

Create Strve is a project building tool based on strve.js that allows you to build pages easily and flexibly.

Global installation

npm install create-strve -g
Copy the code

Check the version

create-strve -v
Copy the code

Initialize the project

create-strve init <projectName>
Copy the code

Quick learning

The easiest way to try strve.js is to use direct import CDN links. You can open it in your browser and follow the examples to learn the basics.

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Strve.js</title>
    <style>
        .inner {
            width: 900px;
            margin: 40px auto;
            text-align: center;
            padding: 40px;
            box-shadow: 0 0 20px #ccc;
        }

        button {
            margin: 10px;
        }
    </style>
</head>

<body>
    <div id="app"></div>
    <script type="module">
        import { Strve, updateView, render, emitEvent } from 'https://cdn.jsdelivr.net/npm/strvejs/dist/strve.esm.js';
        const state = {
            arr: [{
                id: '1'.txt: '1'
            }, {
                id: '2'.txt: '2'
            }, {
                id: '3'.txt: '3'
            }, {
                id: '4'.txt: '4'}].msg: 'hello'.a: 2.style: {
                color: 'red'.fontSize: "40px"
            },
            obj: {
                a: {
                    b: {
                        c: 1}}}};function Component1(v) {
            return render/* html */`
                    <h1 onClick=${emitData}>${v}</h1>
                    <ul class="list-group">
                        ${state.arr.map((todo) => render/* html */`<li class="list-group-item">${todo.txt}</li>`)}
                    </ul>
            `
        }

        function emitData() {
            emitEvent('getTit', {
                detail: { title: 'This is title! '}},'.component1')}function App() {
            return render/* html */`
              <div class='inner'>
                  <p style="${state.style}">{state.obj.a.b.c}</p>
                  <input type="text" class="form-control" value=${state.obj.a.b.c}/>
                  <p>${state.msg}</p>
                  <p>${state.a + state.a}</p>
                  <button type="button" class="btn btn-primary" onClick=${useChange}>Change</button>
                  <button type="button" class="btn btn-primary" onClick=${usePush}>Push</button>
                  <div onGetTit=${getTit} class="component1">
                    ${Component1(state.msg)}
                  </div>
              </div >
          `;
        }

        function getTit(event) {
            updateView(() = >{ state.msg = event.detail.title; })}function useChange() {
            updateView(() = > {
                state.arr.splice(1.1, {
                    id: '0'.txt: '0'}); })}let count = 5;
        function usePush() {
            updateView(() = > {
                // state.obj.a.b.c = 3;
                // state.style.color = 'blue';
                // state.arr.length = 2;
                // state.arr[1] = {
                // id: '4',
                // txt: '4'
                // }
                // state.msg = 'world';
                let a = count++;
                state.arr.push({
                    id: a,
                    txt: a
                })
                // state.arr.pop();
                // state.arr.unshift({
                // id: a,
                // txt: a
                // });
                // state.arr.shift();
            });
            // 'useFkey'
        }

        Strve('#app', {
            data: { state },
            template: App
        });
    </script>
</body>

</html>
Copy the code

If you want to learn more about strve.js, you can read on.

use

API

Strve
  • Parameters:

    • string
    • object
  • Details:

Initialize strve.js. The first parameter is passed in the name of the node selector that you want to mount to the HTML page. The second argument is passed to an object. The first property, data, means a state object. The second property, Template, means a template function.

Strve('#app', {
    data: { state },
    template: App
});
Copy the code
render
  • Type:function
  • Details:

Render is a tag function whose syntax is to take a template string directly after the function name and take arguments from the interpolation in the template string. For example, you can write HTML tags directly in template strings.

function App() {
    return render` 
      

Hello

`
; } Copy the code

If you’re using VSCode, you can download the comment-tagged-templates plugin from the store and add /* HTML */ to render.

Just like this, it makes HTML tag characters highlighted.

function App() {
    return render/*html*/` 
      

Hello

`
; } Copy the code
updateView
  • Parameters:
    • function
    • string(optional)
  • Details:

The first argument is a function. The function body needs to execute values that will change the state of the page, such as state.msg in the following example.

const state = {
    msg:'1'
};

function App() {
    return render`
        <div class='inner'>
            <button onClick=${useChange}>change</button>
            <p>{state.msg}</p>
        </div >
    `;
}

function useChange() {
    updateView(() = > {
        state.msg = '2';
    });
}
Copy the code

The second argument is a string. When you render a page using a list, inserting data into the list header requires binding the useFkey field to avoid DOM nodes being rendered repeatedly.

const state = {
    arr: [1.2]};function Home() {
    return render`
        <div class='inner'>
            <button onClick=${useUnshift}>unshift</button>
            <ul>
                ${state.arr.map((item) => render`<li>${item}</li>`)}
            </ul>
        </div>
    `
}

function useUnshift() {
    updateView(() = > {
        state.arr.unshift('2');
    }, 'useFkey')}Copy the code
emitEvent
  • Parameters:

    • string
    • dictionary
    • string
  • Details:

Custom events are typically used when child components pass data to parent components. The first argument is a string representing the name of the event. The second argument is a dictionary type argument.

  • “Detail”, any type of data whose optional default value is NULL, is a value associated with an event.
  • Bubbles A Boolean value indicating whether the event can bubble. From EventInit. Note: Test Chrome does not bubble by default.
  • Cancelable A Boolean value indicating whether the event can be cancelled.

The third argument is a string, mainly the name of the node selector, where the node refers to the DOM node that the child wraps around the parent component.

Such as:

function Component1(v) {
    return render`
        <h1 onClick=${emitData}>${v}</h1>
    `
}

function emitData() {
    emitEvent('getTit', {
        detail: { title: 'This is title! '}},'.component1')}function App() {
    return render`
        <div class='inner'>
            <div onGetTit=${getTit} class="component1">
            ${Component1(state.msg)}
            </div>
        </div >
    `;
}

function getTit(event) {
    updateView(() = > {
        console.log(event.detail.title); state.msg = event.detail.title; })}Copy the code

The interpolation

Strve.js uses JavaScript based template string syntax to allow developers to declaratively bind DOM to the data of the underlying instance. All strve.js template strings are valid HTML, so they can be parsed by standards-compliant browsers and HTML parsers.

At the bottom of the implementation, strve.js compiles template strings into virtual DOM rendering functions and minimizes DOM operations.

In Strve.js, you can use JavaScript template strings to your heart’s content, and feel its unique charm!

The text

The most common form of data binding is text interpolation using the symbol ${} :

const state = {
    msg: 'hello'
};

function App() {
    return render`
        <div class='inner'>
            <p>${state.msg}</p>
        </div >
    `;
}
Copy the code

Alternatively, you can use a simpler notation, {}, to achieve the desired effect.

const state = {
    msg: 'hello'
};

function App() {
    return render` 
      

{state.msg}world

`
; } Copy the code

However, it is important to note that using this notation {} only applies to text interpolation within the tag. For example, it doesn’t work, but you can use the powerful symbol ${}.

// Bad
function App() {
    return render` 
      
`
; } // Good function App() { return render` <div class='inner'> <input type="text" value=${state.msg}/> </div > `; } Copy the code
expression

Currently, only expressions are supported in the ${} symbol.

Such as:

const state = {
    a: 1.b: 2
};

function App() {
    return render`
        <div class='inner'>
            <p>${state.a + state.b}</p>
        </div >
    `;
}
Copy the code

Attributes bind

Earlier, we saw that we could bind a value to the property value using the symbol ${}.

function App() {
    return render`
        <div class='inner'>
            <input type="text" value=${state.msg}/>
        </div >
    `;
}
Copy the code

In addition, you can bind other properties, such as class.

const state = {
    isRed: true
};

function App() {
    return render`
    <div class='inner'>
        <p class=${state.isRed ? 'red' : ' '}>Strve.js</p>
    </div >
`;
}
Copy the code

If you want to bind the style property, you can do that too.

const state = {
    msg: 'hello'.style: {
        color: 'red'.fontSize: "40px"}};function App() {
    return render`
        <div class='inner'>
            <p style="${state.style}">{state.msg}</p>
        </div >
    `;
}
Copy the code

Conditions apply colours to a drawing

We can also use the ${} symbol, which will only be rendered if the expression returns true.

const state = {
    isShow: false
};

function App() {
    return render`
        <div class='inner'>
            <button onClick=${useShow}>show</button>
            ${state.isShow ? render`<p>Strve.js</p>` : ' '
        }
        </div >
    `;
}

function useShow() {
    updateView(() = >{ state.isShow = ! state.isShow; }); }Copy the code

The list of rendering

We can render a list based on an array with the symbol ${}. For example, we use the map method of arrays to render lists, and we can add items dynamically.

const state = {
    arr: ['1'.'2']};function App() {
    return render`
        <div class='inner'>
            <button onClick=${usePush}>push</button>
            <ul>
            ${state.arr.map((todo) => render`<li>${todo}</li>`)}
            </ul>
        }
        </div >
    `;
}

function usePush() {
    updateView(() = > {
        state.arr.push('3');
    });
}

Copy the code

We mentioned above that updateView() can be passed as a second parameter, which is a string. When rendering a page using a list, you need to bind the useFkey field if you insert data in the head of the list to avoid DOM nodes being rendered repeatedly. Any actions that operate on the head of a list, such as the unshift and pop array methods, require the useFkey field. Other operations do not need this and are already optimized internally.

const state = {
    arr: [1.2]};function Home() {
    return render`
        <div class='inner'>
            <button onClick=${useUnshift}>unshift</button>
            <ul>
                ${state.arr.map((item) => render`<li>${item}</li>`)}
            </ul>
        </div>
    `
}

function useUnshift() {
    updateView(() = > {
        state.arr.unshift('2');
    }, 'useFkey')}Copy the code

The event processing

We can use the ON directive to listen for DOM events and perform some JavaScript when the event is triggered. We recommend using the onClick camel case, but you can also use onClick in all lowercase.

You need to use the symbol ${} to bind events.

function App() {
    return render`
        <div class='inner'>
            <button onClick=${useClick}>sayHello</button>
        }
        </div >
    `;
}

function useClick() {
    console.log('hello');
}
Copy the code

With the Vue. Js collocation

Strve.js can be used not only alone, but also in conjunction with vue.js. You need to call the Strve() registration method after the Vue instance has been mounted, and the first argument already exists in the template tag.

App.vue

<template>
  <div id="container">
    <HelloWorld/>
  </div>
</template>

<script>
import HelloWorld ,{hello} from './components/HelloWorld.vue';
import { about,state } from './components/About.vue';
import { render, Strve } from "strvejs";
const AppTm = () = > render`
      <div>
        ${hello()}
        ${about()}
      </div>
`;
export default {
  name: "App".components:{
    HelloWorld
  },
  mounted() {
    Strve("#container", {
      data: {state},
      template: AppTm, }); }};</script>
Copy the code

If you need to share a method with Vue, it is recommended to use it in the setup method.

HelloWorld.vue

<template>
  <div>
    <img src=".. /assets/logo.png" alt="" @click="useCliimg">
  </div>
</template>
<script>
import { render } from "strvejs";
import styles from '.. /assets/hello/hello.module.css';

export const hello = () = >render`
<h2 class="${styles.color}" onClick=${useCliimg}>hello</h2>
`
function useCliimg(){
    console.log(1);
}

export default {
  name:'HelloWorld'.setup(){
    return {
      useCliimg
    }
  }
}
</script>

Copy the code

If, of course, you want to use strve.js entirely in your Vue component, you can. In the end, however, export Default is recommended to export the component name.

About.vue

<script>
import { render, updateView } from "strvejs";
import styles from '.. /assets/about/about.module.css';

export const about = () = >render`
<div>
    <p>{state.msg}</p>
   <h2 class="${styles.color}" onClick=${useClick}>about</h2>
</div>
`
export const state = {
    msg:"hello"
}

function useClick() {
    updateView(() = >{
        state.msg = 'world'; })}export default {
    name:"About"
}
</script>

Copy the code

With the React. Js collocation

Strve.js is more flexible to use with react. js than with vue. js. The Strve() method is also called to register the method after the component’s first rendering.

App.js

import {useEffect} from 'react'
import {Strve,render,updateView} from 'strvejs';
import './App.css';

const state = {
  msg:"Hello"
}

function Home(){
  return render`<h1 onClick=${useClick}>{state.msg}</h1>`
}

function useClick(){
  updateView(() = >{
    state.msg = "World"; })}function App() {
  useEffect(() = >{
    Strve(".App", {data:{state},
      template: Home
    })
  })
  return (<div className="App"></div>);
}

export default App;
Copy the code

tool

create-strve-app

A set of command line tools to quickly build strve.js projects. The Create Strve App goes one step further than the earlier scaffolding, Create Strve, by quickly creating Strve projects directly from commands. The Create Strve App is built with Vite, a new front-end build tool that significantly improves the front-end development experience.

Build your first Strve project
npm
npm init strve-app@latest
Copy the code
yarn
yarn create strve-app
Copy the code
pnpm
pnpm create strve-app
Copy the code
Select a template

You can choose the template according to your needs.

  • strve

Contains only the basic functionality of strve.js. This template is suitable for applications that have only one page in the project and do not jump to other pages.

  • strve-apps

It includes not only the basic strve.js functions, but also the Strve Router, suitable for jumping to multiple pages and slightly more complex applications.

create-strve

As we briefly mentioned earlier, Create Strve is a project builder based on Strve.js that allows you to build pages easily and flexibly. The Create Strve is also built in Vite.

However, the Create Strve App is recommended here as it is more flexible and faster to install.

The installation

Global installation

npm install create-strve -g
Copy the code

Check the version

create-strve -v
Copy the code

Initialize the project

create-strve init <projectName>
Copy the code

strve-router

Strve Router is the official route manager for Strve.js. It integrates deeply with the core of Strve.js, making it easy to build single-page applications.

Currently, only the Hash mode is supported.

start

The easiest way to try Strve Router is to use a direct import CDN link. You can open it in a browser and follow the examples to learn some basic usage.

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>StrveRouter</title>
</head>

<body>
    <div id="app"></div>
    <script type="module">
        import { Strve, render, updateView } from 'https://cdn.jsdelivr.net/npm/strvejs/dist/strve.esm.js';
        import StrveRouter from 'https://cdn.jsdelivr.net/npm/strve-router/dist/strve-router.esm.js';

        const state = {
            msg: 'Hello! '
        };

        const strveRouter = new StrveRouter([{
            path: '/'.template: Home
        }, {
            path: '/about'.template: About
        }]);

        strveRouter.routerHashUpdate(updateView, () = > {
            console.log(strveRouter.param2Obj());
        });

        function Home() {
            return render`
                <div class='innter'>
                    <button onClick="${goAbout}">goAbout</button>
                    <h1>Home</h1>
                </div>
            `
        }

        function About() {
            return render`
                <div class="innter">
                    <button onClick="${goback}">goback</button>
                    <button onClick="${goHome}">goHome</button>
                    <h2>About</h2>
                </div>
            `
        }

        function App() {
            return render`
              <div class='inner'>
                <p>{state.msg}</p>
                ${strveRouter.routerView()}
              </div >
          `;
        }

        function goback() {
            strveRouter.back();
        }

        function goAbout() {
            console.log('goAbout');
            strveRouter.routerLink({
                path: '/about'.query: {
                    id: 1.name: "maomin"}}); }function goHome() {
            console.log('goHome');
            strveRouter.routerLink('/');
        }

        Strve('#app', {
            data: { state },
            template: App
        });
    </script>
</body>

</html>
Copy the code
The installation
npm
npm install strve-router
Copy the code
yarn
yarn add strve-router
Copy the code
pnpm
pnpm add strve-router
Copy the code
use

If you use it in a modular project, you can import the StrveRouter object and instantiate it. The parameters are the routing components that need to be registered, the path attribute represents the path, and the template attribute represents the imported component.

The page is updated to match the path, so you must register a routerHashUpdate() method, pass the first argument to updateViewAPI, and the second argument is a custom method. Finally, the strveRouter instance is exported.

For example, create an index.js file in a Router folder.

import StrveRouter from 'strve-router';
import {updateView} from 'strvejs';

import Home from '.. /template/homepage.js';
import About from '.. /template/aboutpage.js';

const strveRouter = new StrveRouter([{
    path: '/'.template: Home
}, {
    path: '/about'.template: About
}]);

strveRouter.routerHashUpdate(updateView,() = >{
    console.log('router');
});

export default strveRouter
Copy the code

The component that the route matches is rendered to where the routerView() method is located, typically under the main entry file (such as app.js).

import { render } from 'strvejs';
import strveRouter from './router/index';
function template() {
  return render`
        <div class='inner'>
        ${strveRouter.routerView()}
        </div>
    `;
}

export default template;
Copy the code

To jump to the corresponding page, use the strverouter.RouterLink () method to pass the corresponding path and parameters, or simply pass a path string.

import { render } from 'strvejs'
import strveRouter from '.. /router/index.js'

function Home(){
    return render`
        <div>
            <button onClick="${goAbout}">goAbout</button>
            <h1>Home</h1>
        </div>
    `
}

function goAbout(){
    strveRouter.routerLink({
        path: '/about'.query: {
            id: 1.name: "maomin"}}); }export default Home
Copy the code

There are also several ways to do this if you need to go backwards or forwards.

  • strveRouter.forward(): Jumps one page forward
  • strveRouter.back(): One page is displayed
  • strveRouter.go(n): Indicates that n pages are forwarded

In addition, if you perform a routing parameter operation, you want to get the parameter object. To retrieve object information, simply execute the strverouter.param2obj () method.

Finally, we have pre-installed the project configuration for you. You can use the Create Strve App to select the Strve-Apps template.

other

IDE support

Visual Studio Code
  • Template string automatically completes labels

Open settings.json under Settings and add the following code:

"emmet.triggerExpansionOnTab": true."emmet.showAbbreviationSuggestions": true."emmet.showExpandedAbbreviation": "always"."emmet.includeLanguages": {
    "javascript": "html"
}
Copy the code
  • HTML template string highlighting is supported

Download the comment-tagged-templates plug-in. Add /* HTML */ to the render method.

function App() {
    return render/* html */`
        <div class='inner'>
            <p>${state.msg}</p>
        </div >
    `;
}
Copy the code

UI framework

  • Bootstrap5

v5.bootcss.com/

  • Tailwindcss

www.tailwindcss.cn/

Update log

v2.1.0
  • Fixed DOM property assignment problem;
  • Improve string conversion to virtual DOM logic;
v2.0.0
  • Inserting data into the head of the linked list requires binding the useFkey field to avoid repeated DOM node rendering.

  • Hide the “DOM” node event method after rendering

  • Bind Style Style (object);

  • Bind attributes using ${} symbol binding;

  • HTML template string highlighting (comment-ptagged -templates is required for the VSCode editor);

  • Support parent and child components to transmit values to each other;

  • Bootstrap5, Tailwindcss UI framework;

About the author

  • English name: Vam
  • Nickname ID: Maomincoding
  • Github:github.com/maomincodin…
  • Twitter:twitter.com/maomincodin…
  • Wechat public number: the front end of the road through robbery

conclusion

Because of the length of the reason, I introduce so much here! If you are interested in strve.js, check out the official documentation and do some small projects.

Github.com/maomincodin…

Maomincoding. Making. IO/strvejs – doc…

And if there are exchange learning friends can leave a message or pay attention to me, we come on together!

This is the last one of 2021. Thank you for your support and wish you all good health and good luck in the New Year.