<template>
<div></div>
</template>
<script>
export default {
name: "",
components: {},
props: {},
data() {
return {};
},
filters: {},
computed: {},
watch: {},
created() {},
mounted() {
const res = {
template: '床前明${name}\n疑是${start}${end}\n\n举头望${tit}\n低头思${text}\n',
value: {
end: '上霜',
name: '月光',
start: '地',
text: '故乡',
tit: '明月'
}
};
for (const key in res.value) {
res.template = this.replaceString(res.template, key, res.value[key]);
}
console.log(res.template)
},
beforeDestroy() {},
methods: {
replaceString(string, key, value) {
let str = string;
const type = '${' + key + '}';
while (str.indexOf(type) !== -1) {
str = str.replace(type, value);
}
return str;
},
},
};
</script>
<style scoped lang="less">
</style>
vue 根据对象key值替换字符串
最新推荐文章于 2024-04-23 21:34:27 发布
该代码片段展示了在Vue.js中如何使用模板字符串和数据对象来动态替换模板中的变量,并在`mounted`生命周期钩子中执行替换操作。方法`replaceString`用于处理字符串中的占位符。
摘要由CSDN通过智能技术生成