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 :> <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?
CodePudding user response:
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.
CodePudding user response:
In your example, your mistyped el
with e1
and you forgot to create the HTML root element (that will be used to mount the app).
By correcting these errors, it works as you can see here:
let app = {};
let init = (app) => {
app.vue = new Vue({
el: "#vueapp",
data () {
return {
tabsel: "profile",
}
}
});
}
init(app)
.is-active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vueapp">
<ul>
<li :> <a @click="tabsel = 'profile'">My Profile</a></li>
<li :> <a @click="tabsel = 'example'">Example</a></li>
</ul>
</div>
As for the scope, as long as your variables are defined in data
, they are reactive and you can use them in your HTML template.
CodePudding user response:
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:>
My Profile
</div>
</div>