Day11 - 用 v-model 做父子元件间的双向绑定

今天继续跟大神 重新认识 Vue.js | Kuro Hsu v-model 与元件的双向绑定 (Vue 3.x 新增) 学习学习

下列 childProp0 与 childProp1 与 childProp2 的效果一样,都会从父元素传资料到子元素的 props 中,并且当子元素的 props 更动时,皆会触发使父元素的资料跟着更动

<div id="app">
    <h1>{{ parentMessage }}</h1>
    
    <!-- 没有指定 props 名称的 v-model 绑定 -->
    <child-input0 v-model="parentMessage"></child-input0>
    
    <!-- 指定 props 名称为 childProp1 的 v-model 绑定 -->
    <child-input1 v-model:child-prop1="parentMessage"></child-input1>
    
    <!-- v-bind 搭配 event -->
    <child-input2 :child-prop="parentMessage" @update:child-prop="parentMessage = $event"></child-input2>
</div>
const app = Vue.createApp({
  data() {
    return {
      parentMessage: "父母与子女沟通中"
    };
  }
});


app.component("child-input0", {
  // 名称设为 modelValue 才能接收没有指定 props 名称的 v-model 资料
  props: ["modelValue"],
  template: `
    // input 的值由 modelValue 决定
    <input :value="modelValue"
    
    // 当 input 事件发生时,向父元素发出讯号,讯号内容为 『嗨!资料名称为 modelValue 的资料已经被更新罗,请利用我现在传给你的事件值作为参数(触发我发送这段对话的 input 事件的该 input value),去做你该做的事,因为你跟我 v-model 双向绑定,所以你该做的事就是更新你的资料(更新你拿来跟我双向绑定的你的资料)
  	@input="$emit('update:modelValue', $event.target.value)">
  `
});

app.component("child-input1", {
  props: ["childProp1"],
  template: `
    <input :value="childProp1"
  	@input="$emit('update:childProp1', $event.target.value)">
  `
});

app.component("child-input2", {
  props: ["childProp"],
  template: `
      <input :value="childProp" 
      @input="$emit('update:childProp', $event.target.value)">
  `
});


app.mount("#app");

今天的纪录到这边,如果路过的大侠有发现有什麽理解有出入的地方,希望能邦帮忙提点一波,乾虾 (っಠ‿ಠ)っ


<<:  Day10 - 今天只先铺底座标轴,明天来画 BMO

>>:  24. 解释 immutable / immutability

Day 30 - 完赛啦!! 做个总结

睽违两年的完赛!!! 经过这两年真的感受到时间跟工作的压力,比起两年前待业中可以好好撰写文章的自己,...

创建App-讨论区界面

踏入讨论区的界面,麻烦的事情开始出现啦,需要在每个主题上插入按键,再插入文字框来显示主题文字,况且跳...

30天零负担轻松学会制作APP介面及设计【DAY 19】

大家好,我是YIYI,今天我要来制做体重的页面。 点哪些地方可以进到这个页面呢? 第一个是从HOME...

30-25 之 DDD 战略设计 1 - 战略设计的目的

接下来我们将要开始重 DDD 的战略设计来开始谈谈,别忘了战略的重点在於 : 如何切 然後还有个金句...

Day 03 - 动态调整的PM职涯规划(2)

图片来源 继续上一篇的目标设定, 有时候我觉得是因为你心中已有一个"既定的目标"...