组件点击事件 显示组件1或组件2 用v-show 该怎么写
时间: 2023-11-19 08:06:02 浏览: 21
你可以使用一个变量来控制组件的显示或隐藏,然后在点击事件中改变这个变量的值。具体实现方法如下:
1. 在Vue实例中定义一个变量,例如showComponent。
2. 在组件1和组件2的标签中加入v-show指令,判断showComponent的值是否为true或false,从而决定显示哪个组件。
3. 在点击事件中,改变showComponent的值。例如,如果点击了按钮1,则将showComponent的值设置为true,显示组件1;如果点击了按钮2,则将showComponent的值设置为false,显示组件2。
示例代码如下:
```html
<template>
<div>
<button @click="showComponent = true">显示组件1</button>
<button @click="showComponent = false">显示组件2</button>
<div v-show="showComponent">
组件1内容
</div>
<div v-show="!showComponent">
组件2内容
</div>
</div>
</template>
<script>
export default {
data() {
return {
showComponent: true
};
}
};
</script>
```
在上面的代码中,我们定义了一个showComponent变量,并将其初始值设置为true。在按钮的点击事件中,使用v-on指令监听点击事件,并根据点击的按钮设置showComponent的值。在组件标签中,使用v-show指令判断showComponent的值,从而显示或隐藏对应的组件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)