在vue组件中使用自定义template,代码如下:(代码摘自ant-design-vue,https://1x.antdv.com/components/table-cn/#components-table-demo-editable-cells)
<template>
<div>
<a-button class="editable-add-btn" @click="handleAdd">
Add
</a-button>
<a-table bordered :data-source="dataSource" :columns="columns">
<template slot="name" slot-scope="text, record">
<editable-cell :text="text" @change="onCellChange(record.key, 'name', $event)" />
</template>
<template slot="operation" slot-scope="text, record">
<a-popconfirm
v-if="dataSource.length"
title="Sure to delete?"
@confirm="() => onDelete(record.key)"
>
<a href="javascript:;">Delete</a>
</a-popconfirm>
</template>
</a-table>
</div>
</template>
<script>
const EditableCell = {
template: `
<div class="editable-cell">
<div v-if="editable" class="editable-cell-input-wrapper">
<a-input :value="value" @change="handleChange" @pressEnter="check" /><a-icon
type="check"
class="editable-cell-icon-check"
@click="check"
/>
</div>
<div v-else class="editable-cell-text-wrapper">
{{ value || ' ' }}
<a-icon type="edit" class="editable-cell-icon" @click="edit" />
</div>
</div>
`,
props: {
text: String,
},
data() {
return {
value: this.text,
editable: false,
};
},
methods: {
handleChange(e) {
const value = e.target.value;
this.value = value;
},
check() {
this.editable = false;
this.$emit('change', this.value);
},
edit() {
this.editable = true;
},
},
};
export default {
components: {
EditableCell,
},
data() {
return {
...省略部分代码
};
},
methods: {
...省略部分代码
},
};
</script>
<style>
...省略部分代码
</style>
执行代码控制台报如下错误:
You are using the runtime-only build of Vue where the template compiler is not available
原因分析:
在vue项目中存在两个运行环境版本(即Compiler 版本、Runtime 版本),从npm 包导出的组件默认是运行时(runtime)构建,不支持template模板语法。
要想支持template语法,我们需要修改vue.config.js文件,使得其支持template语法
解决方法:
1. vue-cli 2.x解决方法
修改vue.config.js文件
configureWebpack: {
resolve: {
alias: {
vue$: "vue/dist/vue.esm.js", // 加上这行配置
}
}
},
ctrl+c关闭项目,重启后问题解决