Reputation: 313
I am using vuejs and depending on whether the user is logged in, I need to adjust the size and content of two divs inside my topbar. So if they aren't logged in it should be like this:
<div id='search' width="400px"></div><div id="login" width="200px"><img></div>
And when they're logged in it should be like this:
<div id='search' width="200px"></div><div id="login" width="400px"><div id='somecontent></div><div id='morecontent'></div></div>
I know i can achieve this by hardcoding both of them entirely and then using v-if statements but I was wondering if there was a better way.
Upvotes: 12
Views: 68688
Reputation: 10852
<div id='search' :style="{width: loggedIn ? '200px' : '400px'}"></div>
<div id="login" :style="{width: loggedIn ? '400px' : '200px'}">
<div id='somecontent' v-if="loggedIn"></div>
<div id='morecontent' v-if="loggedIn"></div>
<img v-if="!loggedIn">
</div>
You can bind style in vuejs by using v-bind
new Vue({
...
data: {
loggedIn: false
}
...
})
Upvotes: 24
Reputation: 4438
You should use the style attribute:
const app = new Vue({
el: '#app',
data: {
loggedIn: false
},
created() {
/*
if (CHECK_IF_USER_HAS_LOGGED_IN) {
this.loggedIn = true
}
*/
},
methods: {
login() { this.loggedIn = true },
logout() { this.loggedIn = false }
}
});
#search, #login {
border: solid 1px black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
<button v-on:click="login()">Log in</button>
<button v-on:click="logout()">Log out</button>
<div id='search' v-bind:style="{width: loggedIn ? '400px' : '200px'}">Search Stuff</div>
<div id="login" v-bind:style="{width: loggedIn ? '200px' : '400px'}">
<img v-if="!loggedIn" src="http://via.placeholder.com/350x150">
<template v-if="loggedIn">
<div id="somecontent">some content</div>
<div id="morecontent">more content</div>
</template>
</div>
</div>
Upvotes: 0
Reputation: 555
create a default width inside your data with the default value, like:
data() {
return {
myWidth: '200'
}
},
everytime you login you should change the width value, and then you can do something like this:
<div :style="{ width: myWidth + 'px' }" id='search' width="400px"></div>
hope it helps!
Upvotes: 15