Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js access variables with indefinite name [duplicate]

I wanted to know if it's possible to access variables from vue's data collection, but only by specifying the variable name through another variable. This is what I mean:

Some of my variables/properties:

var siteAdminVue = new Vue({
  el: "#siteAdmin",
  data: {
    tagtitle: "",
    tagparent: "",
    tagdesc: "",
    badgestitle: "",                    
    badgesdesc: "",               
    badgesprivilege: 0,                  
    newstitle: "",                    
    newsnotify: false,                  
    newscontent: "", 
}             

And now I want to set some of these properties in one of my methods in vue:

  var self = this;
  var type = currentSection.toString().substr(4);
  var selectElement = document.getElementById(currentSection + "select");

  // name of vue property, for example newstitle
  var titleElement = type + "title";    

  self.[titleElement]= selectElement.value;

I don't want to use a switch statement to check if I need to set newstitle, badgestitle and so on, so I thought I could store the name in a variable which is already defined in vue and then set it. Is there a way to do this?

Thanks in advance

like image 738
Blade Avatar asked Mar 24 '17 14:03

Blade


1 Answers

Sure, you can treat Vue's data as a js object, meaning you can get and set properties through dot/bracket notation.

Have you tried it? self[titleElement]= selectElement.value; should work.

like image 169
Eric Guan Avatar answered Nov 20 '22 19:11

Eric Guan