使用Vue语法渲染你的Koa视图文件?

前言

Koa是Express团队开发新一代Node Web应用开发框架,当你使用她开发你的Web应用时,一件很重要的事肯定就是——怎样渲染我的视图?

很多人想,那还不简单,选择一个模板引擎,再找个对应支持该引擎的Koa中间件不就行了;
答案是这样的,你也能找到类似下面一堆的中间件:
《使用Vue语法渲染你的Koa视图文件?》

但是有没有想过,直接用Vue的语法与渲染你的视图?于是你找了很多地方,你并不一定找到很好的方案,找到更多的也许是Vue ssr集成方案上去了,但是那个有很多麻烦的地方,它的比较好的使用场景是前后端同构开发;

而你现在只想简单的,要Vue的语法,和他的一些其他核心特性,如:组件化、指令、过滤器等;有没有这样一个现成Koa中间件?

有!!!

合适的中间件

正是因为我有上面的需求,同时也没有找到类似的解决方案,所以我自己基于Vue的服务端渲染方案封装了一个Koa中间件,可以实现上面的所有需求,她的地址:

https://github.com/imingyu/ko…

可以查看git仓库中test文件夹,里面涉及了场景需求的单元测试,均已通过,可以放心使用

此中间件目前支持Koa2版本,最近我会更新下,让她也支持Koa1;

安装

npm i -S koa-vue-view

使用

<!--模板: ./views/Master.vue -->
<template>
    <html lang="zh-CN">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>{{hight(app.name)}} - {{app.version}}</title>
        <slot name="meta"></slot>
    </head>

    <body>
        <h1>{{layoutName}} - {{layoutVersion}}</h1>
        <slot name="top"></slot>
        <slot></slot>
        <slot name="bottom"></slot>
    </body>

    </html>
</template>

<!--组件: ./components/Age.vue -->
<template>
    <strong style="color:red;">
        <slot></slot>
    </strong>
</template>


<!--页面: ./views/User.vue -->
<template>
    <Master>
        <ul>
            <li v-for="(item,index) in users" :key="index">{{item.name}} <Age>{{ add(item.age, 1) }}</Age></li>
        </ul>
    </Master>
</template>
var path = require('path');
var Koa = require('koa');
var VueView = require('koa-vue-view');

var app = new Koa();
app.use(VueView({
    methodName: 'render',//在koa ctx注册渲染视图的方法名,默认render
    data: {
        _: require('lodash'),
        app: {
            name: 'Github',
            version: '1.0.0'
        }
    },
    methods: {
        add(a, b) {
            return a + b;
        }
    },
    components: {
        Master: {
            path: path.resolve(__dirname, './views/Master.vue'),
            data() {
                this.layoutVersion = '1.0.0';
                return {
                    layoutName: 'master'
                }
            },
            methods: {
                hight(str) {
                    return `***${str}***`;
                }
            }
        },
        Age: path.resolve(__dirname, './components/Age.vue')
    }
}));

app.use(ctx => {
    ctx.state.users = [{
        name: 'Tom',
        age: 20
    }, {
        name: 'Alice',
        age: 18
    }];
    ctx.render(path.resolve(__dirname, './views/User.vue'));
    /*
    或者
    ctx.render({
        path:path.resolve(__dirname, './views/User.vue'),
        data(){
            return {name:'Github'}
        },
        methods:{
            show(){}
        }
    });
    */
})


app.listen(8200);

运行上述代码后,你就会发现,哇塞!! 可以在Koa视图里欢快的玩耍Vue啦,欧耶!

    原文作者:imingyu
    原文地址: https://segmentfault.com/a/1190000011512460
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞