75、 vue的插件開(kāi)發(fā)和混入mixin使用

1.本地開(kāi)發(fā)

1.1 初始化本地開(kāi)發(fā)項(xiàng)目

我們采用vue-cli,初始化一個(gè)vue 項(xiàng)目。這個(gè)不做詳解

其他的文件目錄不是本節(jié)內(nèi)容重點(diǎn),不做詳解

1.2 test.js 的內(nèi)容 ,這是插件的入口文件

關(guān)于為什么需要在install這個(gè)方法這里添加我們的方法,可以參考官網(wǎng)。https://cn.vuejs.org/v2/guide/plugins.html 這里只是用了其中的一部分的內(nèi)容。

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 里面引入的兩個(gè)vue 文件,這兩個(gè)文件就是我們需要開(kāi)發(fā)的組件樣式。

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',   // 這里需要注意下,我們是采用的全局注入我們的組件,所以在后面因?yàn)槲覀兊慕M件后,會(huì)直接使用這個(gè)命名的標(biāo)簽
  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>

實(shí)現(xiàn)的效果如下:

image

點(diǎn)擊面板上的數(shù)字,及時(shí)展現(xiàn)在上面,具體的樣式不做詳解,邏輯很簡(jiǎn)單。

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>

效果如下:

這里模擬的是,調(diào)用該插件的toast 方法。

2.本地測(cè)試

我們上面就直接給出了我們要完成的內(nèi)容,但是怎么確定我們這個(gè)寫的樣式或者方法可以用呢? 所以需要測(cè)試下,我們到底寫的是個(gè)什么鬼。

**main.js 全局import **

具體頁(yè)面使用我們的插件:

image
<template>
  <div>
    <div >
      <p>test</p>
      <p>
        <button @click="getChildrenFunction">點(diǎn)擊觸發(fā)子組件的toast</button>
      </p>
      <div>
        <p>點(diǎn)擊面板上的內(nèi)容</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("在父組件里調(diào)用的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>

此時(shí)的this.$data數(shù)據(jù)是



可以看出mixin是可以提供多個(gè)組件重復(fù)使用一個(gè)方法或?qū)傩赃@里先簡(jiǎn)單說(shuō)到這里
  兩個(gè)效果如下:

image

3.打包到npm

測(cè)試完成,可以實(shí)現(xiàn)我們的想要的內(nèi)容。下面我們就要把我們的內(nèi)容打包發(fā)布到npm 上去。

為了不和開(kāi)發(fā)的項(xiàng)目環(huán)境發(fā)生沖突,我們采用另外一個(gè)項(xiàng)目,專門做打包發(fā)布的。

工具:

webpack-simple 這個(gè)簡(jiǎn)化版的webpack。 初始化項(xiàng)目,點(diǎn)擊這里, https://www.cnblogs.com/majj/p/9054471.html。刪掉我們不需要的文件夾,新建一個(gè)我們要放置我們開(kāi)發(fā)代碼,完成如下:

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時(shí)的模塊名,這里便是require("toastPanel")
    libraryTarget: 'umd', //libraryTarget會(huì)生成不同umd的代碼,可以只是commonjs標(biāo)準(zhǔn)的,也可以是指amd標(biāo)準(zhǔn)的,也可以只是通過(guò)script標(biāo)簽引入的。
    umdNamedDefine: true // 會(huì)對(duì) UMD 的構(gòu)建過(guò)程中的 AMD 模塊進(jìn)行命名。否則就使用匿名的 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
    })
  ])
}

打包的項(xiàng)目清單配置文件:

image

執(zhí)行 npm run build 打包

image

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容