为了能在Vue上更简便地使用canvas-nest.js这个炫酷的特效,在原项目作者的提醒下,花了几小时直接将canvas-nest封装成了vue-canvas-nest组件。

初始化


# initvue init webpack-simple vue-canvas-nest# install dependenciescd vue-canvas-nest && npm install

安装原项目依赖


npm install canvas-nest.js

编写组件

仔细阅读一下原项目的README,发现它只有一个API,并且作者已经说明了如何使用,只需传入需要渲染的元素和canvas-nest配置:


// There is only one API, use it like:import CanvasNest from 'canvas-nest.js';const config = {  color: '255,0,0',  count: 88,};// render nest on element with config.const cn = new CanvasNest(element, config);// destroycn.destroy();

将原来的src文件夹重命名为example以便后期当示例和调试使用。

新建src文件夹,并在src文件夹下建立文件vueCanvasNest.vue,代码如下:


<template>  <div class="vue-canvas-nest-element" style="position: absolute;top: 0;left: 0;right: 0;bottom: 0;z-index: -1;">  </div></template>< >import CanvasNest from 'canvas-nest.js';export default {  name: 'vueCanvasNest',  props: {    config: {      type:  ,      default () {        return {          color: '255,0,0',          count: 88,        }      }    }  },  data() {    return {      cn: ''    }  },  mounted() {    const el = document.querySelector('.vue-canvas-nest-element')    this.cn = new CanvasNest(el, this.config)  },  beforeDestroy() {    this.cn.destroy()  }}</ >
同时新建一个叫index.js导出组件


import vueCanvasNest from './vueCanvasNest.vue'export default vueCanvasNest

示例测试

example文件夹下的App.vue文件里加入组件
标签中代码:


import vueCanvasNest from '../'export default {  name: 'app',  components: { vueCanvasNest },  data() {    return {      msg: 'Welcome to Your Vue.js App',      config: {        color: '0,0,255',        count: 200,      }    }  }}

template标签中加入一行:


    <vue-canvas-nest></vue-canvas-nest>

更改webpack.config.js

entry改为 ./src/index.js


module.exports = {    entry: './src/index.js',    ...}

开发环境下entry改为 ./example/main.js


if (process.env.NODE_ENV === 'production') {  ...} else {  module.exports.entry = './example/main.js'}

运行


npm run dev

此时就能看到炫酷的canvas-nest效果了。

发布组件到npmjs


# npm初始化npm init # 按照提示完成package.json后npm publish


原文发布时间为:2018年06月24日
原文作者:ZYSzys__
本文来源: 掘金 如需转载请联系原作者

收藏 打印