首页 > 解决方案 > vue + 纯 html 组件?

问题描述

如何实现 vue-cli 调用纯 html 方法?

请检查下面的示例文件。因为我有自定义的纯 html 代码并且在将其转换为 vuejs 时遇到了困难。

产品.vue

<template>
    <custombutton @childclick="childclick" />
</template>

<script>
export default {
   component: { custombutton },
   methods: {
    childclick(value) {
         console.log(value)
       }
   }
}
</script>

自定义按钮.html

<html>
<body>
 <button @click="childclick" />
</body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<script>
var App = new Vue({
  el: '#app',
  data() {
    return {
      vueMessage: 'testing vue message',
    }
  },

  methods: {
    childclick() {
       this.$emit('childclick', 'success!')
    }

  },
});
</script>
</html>

标签: htmlvue.jsvue-component

解决方案


This solution is a bit more cumbersome, but allows template to be written with syntax highlighting into <script> element, which is more convenient than writing template as a string literal into a template property.

custombutton.js:

export default {
  name: 'CustomButton',
  data: function () {
    return { testVar: 125 }
  }
}

custombutton.component.html: The template is now located in #custombutton-template element. "Hello world! 125" should be printed out.

<!DOCTYPE html>
<html>
<head>
  <title>App</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head>
<body>
  <script id="custombutton-template" type="x-template">
    <div>Hello world! {{ testVar }}</div>
  </script>
  <div id="app"></div>
  <script type="module">
    import CustomButton from "./custombutton.js"
    CustomButton.template = "#custombutton-template"
    
    new Vue({
      el: '#app',
      components: { CustomButton },
      template: '<CustomButton />'
    });
  </script>
</body>
</html>

product.vue: Thanks to Webpack config (see below) we are able to import contents of custombutton.component.html file as a string, parse it and get inner HTML of #custombutton-template element, which is the desired template.

<template>
    <CustomButton />
</template>

<script>
import CustomButton from "./custombutton.js"
import CustomButtonComponent from "./custombutton.component.html"

var el = document.createElement("html")
el.innerHTML = CustomButtonComponent
var template = el.querySelector("#custombutton-template").innerHTML
CustomButton.template = template

export default {
   components: { CustomButton }
}
</script>

Importing custombutton.component.html file as string is done by non-default Webpack raw-loader, therefore it is necessary to adjust Webpack config:

vue.config.js:

module.exports = {
  runtimeCompiler: true,
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.component\.html$/,
          use: ["raw-loader"]
        }
      ]
    }
  }
}

package.json:

{
  "devDependencies": {
    "raw-loader": "^4.0.2"
  }
}

推荐阅读