VUE--组件间v-model绑定

1、自定义指令

// 父组件-html
<template>
   <div>
      <my-son v-my-model="parentValue"></my-son>
      
      // 支持告知指令子组件接收变量名为"sonValue"(默认为"value")
      <my-son v-my-model:sonValue="parentValue"></my-son>
   </div>
</template>

<script>
   import mySon from "./mySon.vue"

   export default {
    
    
      components: {
    
    mySon},
      data() {
    
    
         return {
    
    
            parentValue: "改我试试!",
         }
      }
   }
</script>
// 子组件-html-默认value
<template>
   <div>
      {
    
    {
    
    value}}
   </div>
</template>

<script>
   export default {
    
    
      data() {
    
    
         return {
    
    
            value: "",
         }
      },
   }
</script>
// 子组件-html-指定sonValue
<template>
   <div>
      {
    
    {
    
    sonValue}}
   </div>
</template>

<script>
   export default {
    
    
      data() {
    
    
         return {
    
    
            sonValue: "",
         }
      },
   }
</script>
// 指令注册
import Vue from "vue";

Vue.directive("myModel", function (el, data) {
    
    
   let son = el.__vue__;
   let parent = son.$parent;
   let sonKey = data.arg ? data.arg : "value";
   let sonVal = son[sonKey];

   if (data.hasOwnProperty("oldValue") && sonVal !== data.oldValue) {
    
    
      // emit
      Vue.set(parent, data.expression, sonVal);
   } else {
    
    
      // get
      Vue.set(son, sonKey, data.value);
   }
})

2、子组件监听

// 父组件-html
<template>
   <div>
      <my-son v-model="parentValue"></my-son>
   </div>
</template>

<script>
   import mySon from "./components/test"

   export default {
    
    
      components: {
    
    mySon},
      data() {
    
    
         return {
    
    
            parentValue: "改我试试!",
         }
      }
   }
</script>
// 子组件-html
<template>
   <div>
      {
    
    {
    
    sonValue}}
   </div>
</template>

<script>
   export default {
    
    
      props:["value"],

      computed: {
    
    
         sonValue:{
    
    
            get(){
    
    
               return this.value;
            },
            set(newVal, oldVal){
    
    
               if(newVal === oldVal) return;
               this.$emit("input", newVal);
            }
         }
      }
   }
</script>

猜你喜欢

转载自blog.csdn.net/qweqwe2277/article/details/113125726