vue3 父子组件双向数据绑定

子组件:./components/toolbar.vue

export default {
  name: "toolbar",
  props: {
    narrow:{
      type:Boolean,
      required:true,
     }
  },
  setup(props,context) {   
    var narrow =ref(props.narrow);
     watch(()=>props.narrow,(val)=>{//查看父组件传过来的值是否变化,从而修改值
     narrow.value=val
   });
    watch(()=>narrow.value,(val)=>{ //查看子组件值是否变化,在赋值给父组件
     context.emit('update:narrow',val)
   });
  function dd (){//修改子组件的值
    console.log(this.narrow)
    this.narrow=!this.narrow
  }
   return {
      narrow,
     dd
    };
  },
  
};
</script>        

父组件

<toolbar v-model:narrow="narrow"/>
<script lang="ts">
import { defineComponent,reactive,ref,toRefs } from "vue";
import toolbar from "./components/toolbar.vue";
export default defineComponent({
  name :'App', 
  components: { toolbar },
  setup() {
    var data=reactive({      
      narrow:false,  
      but:()=>{     //修改父组件的值
      data.narrow=!data.narrow
    }
    });     
    return {
     ...toRefs(data)     
    };   
  },  
});
</script>

 

上一篇:03_样式


下一篇:docker 网络