美文网首页VUE技术与项目Vue
75、 vue的插件开发和混入mixin使用

75、 vue的插件开发和混入mixin使用

作者: world_7735 | 来源:发表于2019-08-12 11:23 被阅读118次

    1.本地开发

    1.1 初始化本地开发项目

    我们采用vue-cli,初始化一个vue 项目。这个不做详解

    其他的文件目录不是本节内容重点,不做详解

    1.2 test.js 的内容 ,这是插件的入口文件

    关于为什么需要在install这个方法这里添加我们的方法,可以参考官网。https://cn.vuejs.org/v2/guide/plugins.html 这里只是用了其中的一部分的内容。

    test.js的代码如下:

    import testPanel from './panel.vue'
    import testToast from './toast.vue'
    let test = {}
    test.install = function (Vue, options) {
      Vue.prototype.$msg = 'Hello I am test.js'
      Vue.prototype.$myMethod = function (arr) {
        if (arr.length < 0) {
          return false
        } else {
          arr = arr.join('连接你我')
          return arr
        }
      }
      Vue.mixin({
          data(){
              return {
                  test1:{
                      name:'wushijie',
                      sex:1
                  }
              }
          },
        created: function () {
          this.kk();
        },
        methods: {
            kk(){
                console.log(this.test1);
            }
        },
        
      })
      Vue.component(testPanel.name, testPanel) // testPanel.name 组件的name属性
      Vue.component(testToast.name, testToast) // testPanel.name 组件的name属性
    }
    export default test
    

    test.js 里面引入的两个vue 文件,这两个文件就是我们需要开发的组件样式。

    panel.vue

    <template>
      <div>
        <div class="number-panel">
          <p v-show="checkedNumber.length>0" class="number-show">{{checkedNumber}}</p>
          <p v-show="!checkedNumber" class="number-show">  </p>
          <ul>
            <li @click="clickThisNumber($event)" v-for="index in 9" :key="index">{{index}}</li>
            <li @click="clickThisNumber($event)">0</li>
          </ul>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: 'test-panel',   // 这里需要注意下,我们是采用的全局注入我们的组件,所以在后面因为我们的组件后,会直接使用这个命名的标签
      data () {
        return {
          checkedNumber: ''
        }
      },
      components: {
      },
      methods: {
        clickThisNumber (e) {
          this.checkedNumber = this.checkedNumber.concat(e.currentTarget.innerHTML)
        }
      }
    }
    </script>
    
    <style>
      .number-show {
        height: 20px;
      }
      .number-panel ul {
        padding: 0;
      }
      .number-panel ul li{
        display: inline-block;
        width: 28%;
        height: 50px;
        line-height: 50px;
        margin-top: 20px;
        background: #ddd;
        border-radius: 8px;
        margin-right: 10px;
      }
      .number-panel ul li input {
        display: none;
      }
    </style>
    

    实现的效果如下:

    image

    点击面板上的数字,及时展现在上面,具体的样式不做详解,逻辑很简单。

    toast.vue

    <template>
      <div>
        <div class="toast"  ref='toastPosition' :class="{active: toastHidden}">
          <div class="toast-warpper">
             {{text}}
          </div>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: 'test-toast',
      data () {
        return {
          text: '',
          toastHidden: false
        }
      },
      created () {
        // this.toastPlugin()
      },
      components: {
      },
      methods: {
        toastPlugin (msg, time) {
          this.text = msg
          this.toastHidden = true
          setTimeout(() => {
            this.toastHidden = false
          }, time)
        }
      }
    }
    </script>
    
    <style>
      .toast {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        width: 0px;
        min-height: 0px;
        text-align: center;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 5px;
        color: #fff;
        transition: all 0.5s;
        z-index: -1;
        opacity: 0;
      }
      .toast.active {
        width: 150px;
        min-height: 25px;
        opacity: 1;
        z-index: 11;
      }
    </style>
    

    效果如下:

    这里模拟的是,调用该插件的toast 方法。

    2.本地测试

    我们上面就直接给出了我们要完成的内容,但是怎么确定我们这个写的样式或者方法可以用呢? 所以需要测试下,我们到底写的是个什么鬼。

    **main.js 全局import **

    具体页面使用我们的插件:

    image
    <template>
      <div>
        <div >
          <p>test</p>
          <p>
            <button @click="getChildrenFunction">点击触发子组件的toast</button>
          </p>
          <div>
            <p>点击面板上的内容</p>
          </div>
          <test-panel ref="panel"></test-panel>
          <test-toast ref="toast"></test-toast>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          testArr: [1, 2, 6],
          test1:{
              name:'zhang',
              age:324,
              
          }
        };
      },
      components: {},
      created(){
        console.log("1222", this.$data);
        console.log("2", this.$myMethod(this.testArr));
        this.$nextTick(() => {
          console.log(this.testArr);
        });
      },
      methods: {
        getChildrenFunction() {
          this.$nextTick(() => {
            this.$refs.toast.toastPlugin("在父组件里调用的toast", 2500);
          });
        }
      }
    };
    </script>
    
    <style>
    .number-show {
      height: 20px;
    }
    .number-panel ul {
      padding: 0;
    }
    .number-panel ul li {
      display: inline-block;
      width: 28%;
      height: 50px;
      line-height: 50px;
      margin-top: 20px;
      background: #ddd;
      border-radius: 8px;
      margin-right: 10px;
    }
    .number-panel ul li input {
      display: none;
    }
    </style>
    

    此时的this.$data数据是



    可以看出mixin是可以提供多个组件重复使用一个方法或属性这里先简单说到这里
      两个效果如下:

    image

    3.打包到npm

    测试完成,可以实现我们的想要的内容。下面我们就要把我们的内容打包发布到npm 上去。

    为了不和开发的项目环境发生冲突,我们采用另外一个项目,专门做打包发布的。

    工具:

    webpack-simple 这个简化版的webpack。 初始化项目,点击这里, https://www.cnblogs.com/majj/p/9054471.html。删掉我们不需要的文件夹,新建一个我们要放置我们开发代码,完成如下:

    image

    修改webpack.config.js的打包名称

    image

    代码如下:

    var path = require('path')
    var webpack = require('webpack')
    
    module.exports = {
      entry: './src/lib/index.js',
      output: {
        path: path.resolve(__dirname, './dist'),
        publicPath: '/dist/',
        filename: 'toastPanel.js',
        library: 'toastPanel', // library指定的就是你使用require时的模块名,这里便是require("toastPanel")
        libraryTarget: 'umd', //libraryTarget会生成不同umd的代码,可以只是commonjs标准的,也可以是指amd标准的,也可以只是通过script标签引入的。
        umdNamedDefine: true // 会对 UMD 的构建过程中的 AMD 模块进行命名。否则就使用匿名的 define。
      },
      module: {
        rules: [
          {
            test: /\.css$/,
            use: [
              'vue-style-loader',
              'css-loader'
            ],
          },      {
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
              loaders: {
              }
              // other vue-loader options go here
            }
          },
          {
            test: /\.js$/,
            loader: 'babel-loader',
            exclude: /node_modules/
          },
          {
            test: /\.(png|jpg|gif|svg)$/,
            loader: 'file-loader',
            options: {
              name: '[name].[ext]?[hash]'
            }
          }
        ]
      },
      resolve: {
        alias: {
          'vue$': 'vue/dist/vue.esm.js'
        },
        extensions: ['*', '.js', '.vue', '.json']
      },
      devServer: {
        historyApiFallback: true,
        noInfo: true,
        overlay: true
      },
      performance: {
        hints: false
      },
      devtool: '#eval-source-map'
    }
    
    if (process.env.NODE_ENV === 'production') {
      module.exports.devtool = '#source-map'
      // http://vue-loader.vuejs.org/en/workflow/production.html
      module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
          'process.env': {
            NODE_ENV: '"production"'
          }
        }),
        new webpack.optimize.UglifyJsPlugin({
          sourceMap: true,
          compress: {
            warnings: false
          }
        }),
        new webpack.LoaderOptionsPlugin({
          minimize: true
        })
      ])
    }
    

    打包的项目清单配置文件:

    image

    执行 npm run build 打包

    image

    相关文章

      网友评论

        本文标题:75、 vue的插件开发和混入mixin使用

        本文链接:https://www.haomeiwen.com/subject/vovyjctx.html