vue 引入配置的常量时,常量内部怎么引用 vue 中的值
主要想实现将一些常量放到 js 中存储,vue 使用时加载,但可能有些变量值需要从 vue 内部获取
<template><div><el-row><template v-for="(item, index) in attrs"><el-col :span="24" :key="index">{{ item.label }}: {{ item.value }} --{{ item.name }}</el-col></template></el-row></div>
</template>
<script>
import {attrs, setAttrs} from './config'
export default {name: "Home",data() {return {name: "张三",attrs};},methods: {},
};
</script>
config.js
export const attrs = [{label: "好1",type: "input",value: "你好1",},{label: "好2",type: "input",value: "你好2",},{label: "好3",type: "input",value: "你好3",name: this.name,},
];
正常都是没问题的,但是 name 值里的 this 是 config.js 执行路径。
解决办法可以换成函数返回常量的方式
export function setAttrs(that) {return [{label: "好1",type: "input",value: "你好1",},{label: "好2",type: "input",value: "你好2",},{label: "好3",type: "input",value: "你好3",name: () => that.name,},]
}
<template><div><el-row><template v-for="(item, index) in attrs"><el-col :span="24" :key="index">{{ item.label }}: {{ item.value }} --{{ item.name && item.name() }}</el-col></template></el-row></div>
</template>
<script>
import {attrs, setAttrs} from './config'
export default {name: "Home",data() {return {name: "张三",attrs: setAttrs(this)};},methods: {},
};
</script>
可以获取到张三值了,方便很多。