+
80
-

如何编写一个vuei组件并打包成umd在浏览器运行?

vue

如何编写一个vuei组件并打包成umd在浏览器运行?


网友回复

+
0
-

1、命令行执行vue create mycomponent

800_auto

版本选择vue2,新建后的src目录

800_auto

整体项目目录:

800_auto

2、在src的components下新建HelloWorld.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p>
      For a guide and recipes on how to configure / customize this project,<br>
      check out the
      <a href="https://cli.vuejs.org" target="_blank" rel="noopener">vue-cli documentation</a>.
    </p>

  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

2、src中的main.js改成一下

import HelloWorld from './components/HelloWorld.vue'

HelloWorld.install = function (Vue) {
  Vue.component(HelloWorld.name, HelloWorld);
};

export default HelloWorld

4、修改package.json

{
  "name": "vue-cli-build-components",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "build:lib": "vue-cli-service build --target lib --name HelloWorld src/libmain.js --dest lib",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.8.3",
    "vue": "^2.6.14"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3",
    "vue-template-compiler": "^2.6.14"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "@babel/eslint-parser"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}

5、命令行输入npm run buld:lib后在lib目录下生成umd文件

800_auto

6、浏览器端vue调用HelloWorld.js组件

<!doctype html><meta charset="utf-8"><title>HelloWorld demo</title>
<head>
<script type="text/javascript" src="https://repo.bfw.wiki/bfwrepo/js/vue.2.7.14.js"></script>
<script src="./HelloWorld.umd.js"></script>
</head>
<body>
<div id="app">

</div>
</body>
<script>
Vue.use(HelloWorld)
var app = new Vue({
  el: '#app',
  components: {
    HelloWorld: HelloWorld.default
  },
  template: '<HelloWorld msg="Hello World!"/>'
})
Vue.use(HelloWorld)
new Vue({
components: {
    'hello-world': HelloWorld
  },
 el: '#app',
 data: function() {
   return {

     }
   }
});
</script>

800_auto

我知道答案,我要回答