VueJS:使用字符串设置变量名 [英] VueJS: Set variable name using string
本文介绍了VueJS:使用字符串设置变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在下面的示例中使用字符串设置变量 myvar
?
我试过这个没有用:
eval('myvar'): 'foo'
解决方案
以下是一个非常粗略和基本的示例,说明您将如何完成这样的事情:
new Vue({el: "#app",数据() {返回 {myVar: '你好'}},方法: {changeVal(varName, newValue) {this[varName] = newValue;}}});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id="应用程序">{{myVar}}<button @click="changeVal('myVar', 'world')">更改 myVar</button>
在这里,我们使用了一个方法,该方法获取变量的名称和将其更改为的值 - 然后将其传递给当前的 vue 模型实例(由方法内部的 this
表示)以修改动态变量名的值.
Is it possible to set a variable myvar
using a string in the example below ?
<script>
export default {
data() {
return {
myvar: 'foo'
};
}
}
</script>
I tried this which didn't work:
eval('myvar'): 'foo'
解决方案
Here is a very crude and basic example of how you would accomplish something like this:
new Vue({
el: "#app",
data() {
return {
myVar: 'hello'
}
},
methods: {
changeVal(varName, newValue) {
this[varName] = newValue;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
{{myVar}}
<button @click="changeVal('myVar', 'world')">change myVar</button>
</div>
Here, we are utilizing a method that takes the name of the variable and the value to change it to - then passing it to the current vue model instance (represented by this
inside of methods) to modify the value of the dynamic variable name.
这篇关于VueJS:使用字符串设置变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文