'Vue.js Variables

I am very new to Vue.js (and html in general), I am attempting to use Vue.js to automate Bulma tab switching without needing many HTML docs.

<li :class="[ tabsel === 'profile' ? 'is-active' : '']"> <a @click="tabsel = 'profile'">My Profile</a></li>

This is an example of one of the lines to swap which tab is active. I am curious where I can initialize the tabsel variable and how does scoping work?

I initially had a .js file that I loaded in as such:

let app = {};

let init = (app) => {
    app.vue = new Vue({
        e1: "#vueapp",
        data () {
            return {
                tabsel: "profile",
            }
        }
    });
}

Ultimately I am not sure if the first code snippet should be able to see this value. What is the proper way to initialize this variable? In my example does this not work because tabsel is a member of data which is not explicitly what the html bit is looking for?



Solution 1:[1]

In vue js, It is called as state. In your case, "tabsel" is a state. The state will be having the data which will be shared within the application. If you create a variable. You cannot take to values to other components easily. That's why states are introduced. If you use vuex, the state created in the vuex can be accessed globally inside the application.

Solution 2:[2]

What is the proper way to initialize this variable ?

In Vue, You can initialize the variable in data() method/object and if you want to make any changes in the value of the variable. You can do that via events or in mounted/created hooks.

Demo as per your code :

new Vue({
    el: '#app',
  data:{
    tabsel: null // Initializing
  },
  mounted() {
    this.tabsel = 'profile'; // Assinging value to the variable
  }
});
.is-active{
  background: #444;
  color: #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-bind:class="{'is-active': tabsel === 'profile' }">
    My Profile
  </div>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sujith Sandeep
Solution 2 Rohìt Jíndal