惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
GbyAI
GbyAI
Google DeepMind News
Google DeepMind News
Jina AI
Jina AI
B
Blog
aimingoo的专栏
aimingoo的专栏
酷 壳 – CoolShell
酷 壳 – CoolShell
T
The Blog of Author Tim Ferriss
Last Week in AI
Last Week in AI
月光博客
月光博客
H
Help Net Security
V
Visual Studio Blog
量子位
A
About on SuperTechFans
博客园 - Franky
人人都是产品经理
人人都是产品经理
N
Netflix TechBlog - Medium
云风的 BLOG
云风的 BLOG
雷峰网
雷峰网
Martin Fowler
Martin Fowler
Microsoft Security Blog
Microsoft Security Blog
博客园 - 叶小钗
P
Proofpoint News Feed
MongoDB | Blog
MongoDB | Blog

小松鼠的博客

记录一次线上k8s工作节点无法创建容器的问题排查思路与解决办法 记一次线上GoLang项目OOM排查过程 从LastPass转向拥抱开源KeePass的心路历程 故障定位与 AI 结合前后端编码实践 FileBeat收集nginx-ingress-controller日志 K8s云原生环境下文件描述符占用过高查询思路 2024年最新关闭火绒安全工具的开机自启方法 Kubernetes任务调度实践-Go语言实现Job和CronJob对比分析 离线更新k8s环境下的trivy漏洞库方法 使用Go语言接入Choerodon实现基于OAuth2的统一身份认证登录 关于docker jdk1.8镜像中的GB18030-2022标准支持及验证 Go框架gin中的session存储gin-contrib-sessions和go-session 关于修改node_module中的源码问题记录 docker-compose网络和内网服务IP冲突问题 慎用存储过程:一条语句引发的数据库存储100%占用 Spring Boot中4种文件下载方法的实现 避坑-不能将specific类型的gitlab-runner改变为share类型 Docker compose中的MySQL主从复制模式和percona-toolkit工具使用 在minio中开启https访问以及使用rclone备份minio桶 在多机Docker环境下部署Choerodon的解决方案 Prometheus中Monitor添加对SpringBoot Actuator的Basic认证 在Nginx的容器镜像中隐藏Nginx的Server响应头 K8s中的两种nginx-ingress-controller及其区别 两个docker工具:runlike和whaler Grafana中的邮件报警和截图插件grafana-image-enderer K8s中externalName-service和services-without-selectors maven配置文件settings.xml中的一些概念总结 K8s中flexvolume插件驱动的安装 K8s中的coredns无法解析svc问题排查 K8s中使用Ingress访问请求体过大问题解决
在Vue2中自定义Switch组件并实现父子组件双向数据绑定
ycyin · 2023-08-11 · via 小松鼠的博客

2023年8月10日大约 3 分钟前端技术VueElement-UISwitcher


基本需求场景:使用Vue2实现一个自定义的Switch Button组件,并且在使用时要求父子组件能相互通信。使用到的技术主要是vue2element-ui

实现效果

效果展示
效果展示

基本思路

按钮样式: 主要参考https://codepen.io/mburnette/pen/LxNxNg

父子组件传值绑定: 主要有两种方式:

第一种父组件给子组件的prop传值,子组件通过this.$emit('change', this.isChecked)向父组件传递change事件,父组件监听change事件变化即可,可参考:Vue.js监听子组件事件(v-on)、绑定子组件数据(v-model)_vue监听子组件数据变化

第二种则是利用Vue2.2.0中新增的model来实现,可参考:API — Vue.js (vuejs.org)在 vue 中使用 v-model 监听子组件中的任何值,这其实是Vue提供的一种可自定义的prop和event的方式。

允许一个自定义组件在使用 v-model 时定制 prop 和 event。默认情况下,一个组件上的 v-model 会把 value 用作 prop 且把 input 用作 event,但是一些输入类型比如单选框和复选框按钮可能想使用 value prop 来达到不同的目的。使用 model 选项可以回避这些情况产生的冲突。

Vue.component('my-checkbox', {
  model: {
    prop: 'checked',
    event: 'change'
  },
  props: {
    // this allows using the `value` prop for a different purpose
    value: String,
    // use `checked` as the prop which take the place of `value`
    checked: {
      type: Number,
      default: 0
    }
  },
  // ...
})
<my-checkbox v-model="foo" value="some value"></my-checkbox>

上述代码相当于:

<my-checkbox
  :checked="foo"
  @change="val => { foo = val }"
  value="some value">
</my-checkbox>

代码实现

示例代码中包含了两种父子组件传值绑定的方式,具体使用时自行选择。

Switcher子组件:

<template>
  <div style="display: flex;align-items: center">
    <span :style="{fontSize: '0.25rem',color: inactiveColor1}">{{inactiveText}}</span>
    <input type="checkbox" id="switch" v-model="isChecked" @change="handleChange" />
    <label for="switch">Toggle</label>
    <span :style="{fontSize: '0.25rem',color: activeColor1}">{{activeText}}</span>
  </div>
</template>

<script>

export default {
  props: {
    activeText: String,
    inactiveText: String,
    activeColor: String,
    inactiveColor: String,
    parentMsg: {
      type: Boolean,
      default: false
    }
  },
  // https://v2.cn.vuejs.org/v2/api/#model
  model: {
    // 父组件使用v-model双向绑定parentMsg值
    prop: 'parentMsg',
    // 定义v-model的事件名为watch111
    event: 'watch111'
  },
  name: 'Switcher',
  data() {
    return {
      isChecked: false,
      activeColor1: this.inactiveColor?this.inactiveColor:"#606266",
      inactiveColor1: this.activeColor?this.activeColor:"#13ce66",
    }
  },
  methods: {
    handleChange() {
      this.$emit('change', this.isChecked)
      this.$emit('watch111', this.isChecked)
      if (this.isChecked) {
        this.activeColor1 = this.activeColor
        this.inactiveColor1 = this.inactiveColor
      }else{
        this.activeColor1 = this.inactiveColor
        this.inactiveColor1 = this.activeColor
      }
    },
  },
}
</script>

<style lang="scss" scoped>

input[type=checkbox]{
  height: 0;
  width: 0;
  visibility: hidden;
}

label {
  cursor: pointer;
  text-indent: -9999px;
  width: 80px;
  height: 30px;
  background: grey;
  display: block;
  border-radius: 100px;
  position: relative;
}

label:after {
  content: '';
  position: absolute;
  top: 5px;
  left: 5px;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 90px;
  transition: 2s;
}

input:checked + label {
  //background: #bada55;
}

input:checked + label:after {
  left: calc(100% - 5px);
  transform: translateX(-100%);
}

label:active:after {
  width: 70px;
}
</style>

父组件中使用Switcher子组件:

使用v-model来绑定子组件this.$emit('watch111', this.isChecked)过来的值,使用@change来监听子组件this.$emit('change', this.isChecked)过来的值

<Switcher active-text="环境视图"
   inactive-text="软件视图"
   active-color="#215ae5"
   inactive-color="#606266"
   v-model="foo" 
   @change="handleSwitch($event)"
/>