Html Vue 更改宽度和内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45730095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vue change width and content
提问by JFugger_jr
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:
我正在使用 vuejs,根据用户是否登录,我需要调整顶部栏中两个 div 的大小和内容。所以如果他们没有登录,它应该是这样的:
<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.
我知道我可以通过完全硬编码它们然后使用 v-if 语句来实现这一点,但我想知道是否有更好的方法。
回答by choasia
<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
您可以使用v-bind在 vuejs 中绑定样式
new Vue({
...
data: {
loggedIn: false
}
...
})
回答by Filipe Costa
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!
希望能帮助到你!
回答by kevguy
You should use the style attribute:
您应该使用 style 属性:
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>