Vue 从本地文件导入 HTML
Vue import HTML from local file
我正在寻找一种从
中的文件中导入 HTML 内容的方法
/src/activities/0/2/content.html
这两个数字是变量。
我需要做类似
的事情
mounted(){
this.foo = require('/src/activities/0/2/content.html')
}
<div>
{{ foo }}
</div>
但我没有找到办法做到这一点。如果有人知道解决方案,那将非常有帮助。
谢谢
首先 Vue 的 webpack 需要了解如何加载 .html
文件。您可以使用 html-loader
。先安装它:
npm install html-loader --save-dev
然后在项目根目录中编辑(或创建)vue.config.js
(不是src
)。来自 the docs:
module.exports = {
chainWebpack: config => {
config.module
.rule('html')
.test(/\.html$/)
.use('html-loader')
.loader('html-loader')
}
};
现在您可以导入 HTML 个文件,例如:
import html from '@/activities/0/2/content.html'
export default {
data() {
return {
html, // es6 property shorthand syntax
foo: null
}
}
}
并像使用任何其他数据变量一样使用 html
。或者您可以按照 require
:
要求的方式进行
mounted(){
this.foo = require('@/activities/0/2/content.html')
}
@
是 src
的别名
我正在寻找一种从
中的文件中导入 HTML 内容的方法/src/activities/0/2/content.html
这两个数字是变量。
我需要做类似
的事情mounted(){
this.foo = require('/src/activities/0/2/content.html')
}
<div>
{{ foo }}
</div>
但我没有找到办法做到这一点。如果有人知道解决方案,那将非常有帮助。
谢谢
首先 Vue 的 webpack 需要了解如何加载 .html
文件。您可以使用 html-loader
。先安装它:
npm install html-loader --save-dev
然后在项目根目录中编辑(或创建)vue.config.js
(不是src
)。来自 the docs:
module.exports = {
chainWebpack: config => {
config.module
.rule('html')
.test(/\.html$/)
.use('html-loader')
.loader('html-loader')
}
};
现在您可以导入 HTML 个文件,例如:
import html from '@/activities/0/2/content.html'
export default {
data() {
return {
html, // es6 property shorthand syntax
foo: null
}
}
}
并像使用任何其他数据变量一样使用 html
。或者您可以按照 require
:
mounted(){
this.foo = require('@/activities/0/2/content.html')
}
@
是 src