两次点击事件切换一组按钮颜色和跳转vue3的路由
两个点击事件切换两个按钮,点击时跳转路由,改变当前颜色,点击另一个,然后相同
我可以改变颜色或跳过路线,但这两者不能同时进行。我只能在双击后更改颜色。
<button :class="isRed ? 'red-button':'blue-button'" @click="handleRoute()">red-button</button>
<button :class="isRed ? 'red-button':'blue-button'" @click="handleRoute()">blue-button</button>
function handleRoute(){
isRed.value = !isRed.value;
if (isRed.value) {
router.push('/')
} else {
router.push('/about')
}
}
<template>
<div>
<button :class="isRed ? 'red-button' : 'blue-button'" @click="handleClick(1)">Button 1</button>
<button :class="isRed ? 'red-button' : 'blue-button'" @click="handleClick(2)">Button 2</button>
</div>
</template>
<script>
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
export default {
setup() {
const router = useRouter()
const state = reactive({
isRed: false,
clickedButton: 0
})
const handleClick = (buttonNum) => {
if(buttonNum === state.clickedButton) {
state.isRed = !state.isRed
if(state.isRed) {
router.push('/')
} else {
router.push('/about')
}
}
state.clickedButton = buttonNum
}
return {
isRed: state.isRed,
handleClick
}
}
}
</script>
<style>
.red-button {
background: red;
color: white;
}
.blue-button {
background: blue;
color: white;
}
</style>
有点晕。有双击事件可以解决你的需求吗https://developer.mozilla.org/zh-CN/docs/Web/API/Element/dblclick_event
首先了解父子组件生命周期执行顺序 ==>
加载渲染数据过程
父组件 beforeCreate -->
父组件 created -->
父组件 beforeMount -->
子组件 beforeCreate -->
子组件 created -->
子组件 beforeMount -->
子组件 mounted -->
父组件 mounted -->
原因:因为生命周期只会执行一次,数据是要等到异步请求以后才能拿到,那么子组件的mounted钩子执行的时候,还没有拿到父组件传递过来的数据,但是又必须要打印出来结果,那这样的话,就只能去打印props中的默认值空字符串了,所以打印的结果是一个空字符串。
解决办法:
使用v-if控制组件渲染的时机
初始还没拿到后端接口的异步数据的时候,不让组件渲染,等拿到的时候再去渲染组件。使用v-if="变量"去控制,初始让这个变量为false,这样的话,子组件就不会去渲染,等拿到数据的时候,再让这个变量变成true,
举例:
data() {
return {
isTrue:false // 初始为false
};
},
monted(){
this.$post.a.b.c.getData(res=>{
if(res.result){
this.isTrue = true
}
})
}
使用watch监听数据的变化
举例:
props: {
tableData: {
type: Array,
default: [],
},
},
watch: {
tableData(val){
console.log(val)
}
},
使用VueX