版权声明:未经本人同意不得私自转载 https://blog.csdn.net/qq_40190624/article/details/85257163
需求: 同一个button在不同页面使用,只有文字不一样;有的内容为登录有的为注册
下面我们自封一个button组件
子组件:
<template>
<!-- :type="type" 为按钮类型 :disabled="disabled" 为判断他为false还是ture
{'is-disabled':disabled} 如果为true就可以有is-disabled的样式
@click="$emit('click')" 传入一个cklick点击事件
-->
<button
class="y-button"
:class="{'is-disabled':disabled}"
:type="type"
:disabled="disabled"
@click="$emit('click')"
>
<slot>
<!-- 这是一个插槽在父组件中可以放入登录或都注册的文本字段 -->
</slot>
</button>
</template>
<script>
export default {
name:'ybutton',
props:{//传值去到父组件
type:String,
disable:{//传值类型,默认值为false
type:Boolean,
default:false
}
}
}
</script>
<style scoped>
/* 获取焦点的时候和hover的时候改变颜色 */
.is-disabled:focus,
.is-disabled:hover{
background: blue;
color:white;
}
</style>
父组件引用:
<template>
<div>
<input type="text" v-model="use.email">
<div class="btn_wrap">
<Ybutton :disabled="isDisabled" @click="loginClick">登录</Ybutton>
</div>
</div>
</template>
<script>
// 引入button组件
import Ybutton from "./Ybutton"
export default {
data(){
return{
user:{
email:''
}
}
},
components:{//注册组件
Ybutton
},
computed:{//监听子组件的disabled用于启用或禁用按钮
isDisabled(){
if(this.user.email){
// 如果input框有值就让disabled为false 不禁用
return false;
}else{
return true;
}
}
},
methods:{
loginClick(){
// 实现登录,存储token
this.$axios.post('/api/users/login',this.user).then(res =>{
// res 结果用会返回token 我们可以用解构模式给他存储
const { token } = res.data;
// 存储ls
localStorage.setItem('wxToken',token);
//存储之后页面进行主页跳转
this.$router.push('/')
})
}
}
}
</script>