详解VUE自定义组件中用.sync修饰符与v-model的区别

春风如梦风过无痕,只为心的思念,遥寄一份浓浓的祝福。决不能习惯失败,因为你要知道,身体的疲惫,不是真正的疲惫;精神上的疲惫,才是真的劳累。

.sync修饰组件

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>vue-03</title>
  <!-- 引入Vue -->
  <link rel="nofollow noopener noreferrer" href="https://cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" rel="stylesheet">
  <script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
</head>

<body>

  <div class="container" style="margin-top: 12px;">
    <div id="demo" class="row">
      {{ say }}
      <br />
      <my-input :value.sync="say"></my-input>
    </div>
  </div>


  <script>
    new Vue({
      el: '#demo',
      data: {
        say: "123"
      },
      components: {
        "my-input": {
          props: ['value'],
          template: "<div><input v-bind:value='value' v-on:input='change1' />{{value}}</div>",
          watch: {
            value: function(newValue, oldValue) {
              alert('子组件value新旧值' + newValue + '/' + oldValue);
              //this.$emit('update:value', newValue)
            }

          },
          methods: {
            change1: function(e) {
              var v = e.target.value
              this.$emit('update:value', v)
            },

          }
        }
      },
      watch: {
        say: function(n, o) {
          alert('父组件新旧值' + n + '-' + o)
        }
      },
      methods: {

      }
    })
  </script>
</body>

v-model修饰组件

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>vue-10</title>
  <!-- 引入Vue -->
  <link rel="nofollow noopener noreferrer" href="https://cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" rel="stylesheet">
  <script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
</head>

<body>

  <div class="container" style="margin-top: 12px;">
    <div id="demo" class="row">
      {{ say }}
      <br />
      <my-input v-model="say"></my-input>
    </div>
  </div>


  <script>
    new Vue({
      el: '#demo',
      data: {
        say: "123"
      },
      components: {
        "my-input": {
          props: ['value'],
          template: "<div><input v-bind:value='value' v-on:input='change' />{{value}}</div>",
          watch: {
            value: function(newValue, oldValue) {
              alert('子组件value新旧值' + newValue + '/' + oldValue);
              //this.$emit('update:value', newValue)
            }

          },
          methods: {
            change: function(e) {
              this.$emit('input', e.target.value)
            }
          }
        }
      }
    })
  </script>
</body>

区别只能自己慢慢体会,个人感觉 .sync用法灵活,而v-model只能接受prop名为为value的值.

两者都需要手动触发$emit方法.

本文详解VUE自定义组件中用.sync修饰符与v-model的区别到此结束。用平常心来生活,用惭愧心来待人。小编再次感谢大家对我们的支持!

您可能有感兴趣的文章
Vue路由参数的传递与获取方式详细介绍

vue学习记录之动态组件浅析

如何解决ElementUI组件中el-upload上传图片不显示问题

解读element el-upload上传的附件名称不显示 file-list赋值

一篇关于el-table-column的formatter的如何使用及说明