vue.jsのdataに定義された変数を文字列で指定したい
- 以下のように定義されているとする
- この時にthis.firstValueを"this.firstValue"の様に文字で指定してthis.firstValueに値を入れたいとする
<script> new Vue({ el: "#app", vuetify: new Vuetify(), components: {}, data: { firstValue: null, secondValue: null, insertData: [{ "key": "firstValue", "value": "foo" }, { "key": "secondValue", "value": "bar" }] }, created() { this.insertData.forEach(element => { const key = "this." + element.key let v = eval(key); v = element.value }); }, methods: {}, computed: {}, watch: {} }) </script>
this.変数名はthis[変数名]で参照ができる
- この様な場合vueでは以下のように書くことができる
- this["firstValue]とするとthis.firstValueに値を入れることができる
<script> new Vue({ el: "#app", vuetify: new Vuetify(), components: {}, data: { firstValue: null, secondValue: null, insertData: [{ "key": "firstValue", "value": "foo" }, { "key": "secondValue", "value": "bar" }] }, created() { this.insertData.forEach(element => { this[element.key] = element.value; }); }, methods: {}, computed: {}, watch: {} }) </script>
ソース全文
ソース全文
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.x/css/materialdesignicons.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"> <title>Document</title> </head> <body> <div id="app"> <v-app> <v-main> <v-container> <v-card> <v-card-title>dataの中の変数をthis+文字列で値を入れる</v-card-title> <v-card-text>{{ firstValue }}</v-card-text> <v-card-text>{{ secondValue }}</v-card-text> </v-card> </v-container> </v-main> </v-main> </v-app> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script> <script src="https://cdn.jsdelivr.net/npm/vue-router@3.5.3/dist/vue-router.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script src="https://unpkg.com/http-vue-loader"></script> <script> new Vue({ el: "#app", vuetify: new Vuetify(), components: {}, data: { firstValue: null, secondValue: null, insertData: [{ "key": "firstValue", "value": "foo" }, { "key": "secondValue", "value": "bar" }] }, created() { this.insertData.forEach(element => { this[element.key] = element.value; }); }, methods: {}, computed: {}, watch: {} }) </script> </body> </html>