300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > vue——点击按钮实现不同元素或组件显示和隐藏(切换)

vue——点击按钮实现不同元素或组件显示和隐藏(切换)

时间:2020-10-24 00:42:41

相关推荐

vue——点击按钮实现不同元素或组件显示和隐藏(切换)

默认

再次点击组件一按钮组件一面板隐藏,按钮样式也发生改变

切换按钮后,面板发生改变

1、同一组件中实现不同元素切换

<template><div class="page"><div class="button"><span @click="show(1)":class="index===1? 'active':''">组件一</span><span @click="show(2)":class="index===2? 'active':''">组件二</span><span @click="show(3)":class="index===3? 'active':''">组件三</span></div><!-- 面板一 --><div class="one"v-show="index===1 && isShow"></div><!-- 面板二 --><div class="two"v-show="index===2 && isShow"></div><!-- 面板三 --><div class="three"v-show="index===3 && isShow"></div></div></template><script>export default {data () {return {// 控制切换按钮后按钮改变样式index: 1,// 控制点击按钮后子组件显示,再次点击隐藏isShow: true}},methods: {show (value) {this.index === value ? this.isShow = !this.isShow : this.isShow = truethis.index = value}}}</script><style scoped lang="scss">.page {padding: 20px;.button {span {display: inline-block;height: 40px;line-height: 40px;text-align: center;width: 100px;border: 1px solid #e6e6e6;cursor: pointer;}.active {color: #ffffff;background: rgb(49, 49, 238);}}.one {height: 300px;background: red;}.two {height: 300px;background: yellow;}.three {height: 300px;background: blue;}}</style>

2、利用< keep-alive >和< component >实现不同子组件切换,效果一样

子组件一:one.vue

<template><div class="one-com">11111</div></template><style scoped lang="scss">.one-com {height: 300px;background: red;}</style>

子组件二:two.vue

<template><div class="one-com">22222</div></template><style scoped lang="scss">.one-com {height: 300px;background: yellow;}</style>

子组件三:three.vue

<template><div class="one-com">333333</div></template><style scoped lang="scss">.one-com {height: 300px;background: blue;}</style>

父组件

<template><div class="page"><div class="button"><span @click="show(1)":class="index===1? 'active':''">组件一</span><span @click="show(2)":class="index===2? 'active':''">组件二</span><span @click="show(3)":class="index===3? 'active':''">组件三</span></div><div class="tab_content"><keep-alive><component :is="comp"v-show="isShow"></component></keep-alive></div></div></template><script>import one from '@/components/dynamic/one.vue'import Two from '@/components/dynamic/two.vue'import Three from '@/components/dynamic/three.vue'export default {components: {one, Two, Three },data () {return {// 控制切换按钮后按钮改变样式index: 1,// 控制子组件显示comp: 'one',// 控制点击按钮后子组件显示,再次点击隐藏isShow: true}},methods: {show (value) {if (this.index === value) {this.index = 0this.isShow = !this.isShow} else {this.index = valuethis.isShow = true}if (value === 1) p = 'one'if (value === 2) p = 'two'if (value === 3) p = 'three'}}}</script><style scoped lang="scss">.page {.button {span {display: inline-block;height: 40px;line-height: 40px;text-align: center;width: 100px;border: 1px solid #e6e6e6;cursor: pointer;}.active {color: #ffffff;background: rgb(49, 49, 238);}}}</style>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。