簡體   English   中英

Vue + Typescript + webpack:將html導入組件

[英]Vue + Typescript + webpack: Import html into component

我有一個typescript + vue + webpack應用程序,我想從代碼中單獨的html。
我已經按照本教程編寫了一個簡單的Hello Word。

Webpack配置

const path = require('path');

module.exports = {
    mode: "development",
    entry: './src/app.ts',
    output: {
        path: path.resolve('dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.(ts|tsx)?$/,
                loader: 'ts-loader',
                exclude: /node_modules/                
            },
            {
                test: /.html$/,
                loader: "vue-template-loader",
                exclude: /index.html/
            }
        ]
    },
    resolve: {
        extensions: [
            '.js',
            '.vue',
            '.tsx',
            '.ts'
        ]
    }
};

HTML

<div>
    <h2>Hello from {{message}}</h2>
</div>

Vue組件

import Vue from "vue";
import Component from "vue-class-component";
// template: '<button @click="onClick">Click!</button>'
import WithRender from "./home.html";

@WithRender
@Component
export default class HomeComponent extends Vue {

    public message: string = "Word";

    constructor() {
        super();
    }

    mounted() { }
}

我添加了這個墊片后

declare module '*.html' {

        import Vue, { ComponentOptions, FunctionalComponentOptions } from 'vue'
        interface WithRender {
            <V extends Vue, U extends ComponentOptions<V> | FunctionalComponentOptions>(options: U): U
            <V extends typeof Vue>(component: V): V
        }

        const withRender: WithRender
        export default withRender
}

我(幾乎)了解了typescript 裝飾器是如何工作的,但我不理解填充碼,這段代碼如何 html注入Vue組件?

我已經從Typescript網站了解裝飾器

vue-template-loader將HTML模板編譯為render函數, @WithRender將其插入到類定義中。

例如,這個HTML:

<div>Hello world</div>

轉換為此render函數:

render(h) {
  return h('div', 'Hello world')
}

然后,將@WithRender (將上面的示例HTML模板導入的結果)應用於class Foo extends Vue {}導致:

class Foo extends Vue {
  render(h) {
    return h('div', 'Hello world')
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM