用vue双向绑定写开关

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./vue.js"></script>
    <style>
      .one {
        border-radius: 30px;
        position: relative;
        top: 0;
        left: 0;
        margin-top: 30px;
      }
      .two {
        border-radius: 50%;
        position: absolute;
        top: 0;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <label> 开关: <input type="checkbox" v-model="hobby" /></label>
      <com v-model="hobby" :width="100" :height="30"></com>
      <com v-model="hobby" :width="60" :height="30"></com>
    </div>

    <template id="com">
      <div>
        <div class="one" :style="hear">
          <div class="two" :style="ball" @click="ment($event)"></div>
        </div>
      </div>
    </template>

    <script>
      let com = {
        template: "#com",
        props: {
          value: Boolean,
          width: Number,
          height: Number,
        },
        // 子传父方法
        methods: {
          ment() {
            // console.log(event);
            // console.log(event.pageX);
            // console.log(event.target);
            let target = event.target;
            if (event.pageX < 50) {
              (target.style.left = this.width.left = 0 + "px"),
                this.$emit("input", true);
            } else {
              (target.style.left = this.width.right = 0 + "px"),
                this.$emit("input", false);
            }
          },
        },
        // 父传子样式
        computed: {
          hear() {
            if (this.value) {
              return {
                width: this.width + "px",
                height: this.height + "px",
                "background-color": "red",
              };
            } else {
              return {
                width: this.width + "px",
                height: this.height + "px",
                "background-color": "gray",
              };
            }
          },
          ball() {
            if (this.value) {
              return {
                width: Math.floor(this.width / 3) + "px",
                height: this.height + "px",
                "background-color": "white",
                right: 0,
              };
            } else {
              return {
                width: Math.floor(this.width / 3) + "px",
                height: this.height + "px",
                "background-color": "white",
                left: 0,
              };
            }
          },
        },
      };

      let vm = new Vue({
        el: "#app",
        data: {
          hobby: true,
        },
        components: {
          com,
        },
      });
    </script>
  </body>
</html>
 
效果如下:

 

 

 

 

posted @ 2020-12-17 22:22  阳菜  阅读(214)  评论(0)    收藏  举报