vue双向绑定

最常用的不同组件之间双向绑定的方式是使用 v-model 结合自定义事件和 props。这种方式可以使得代码更加简洁和易于理解。

具体来说,可以通过在子组件中使用 v-model,并且在子组件中触发 update:modelValue 事件来实现双向绑定。

<!-- ChildComponent.vue -->
<template>
  <div>
    <label>Child Component:</label>
    <input v-model="innerValue">
  </div>
</template>

<script>
export default {
  props: ['modelValue'],
  data() {
    return {
      innerValue: this.modelValue
    };
  },
  watch: {
    modelValue(newValue) {
      this.innerValue = newValue;
    }
  },
  methods: {
    updateValue() {
      this.$emit('update:modelValue', this.innerValue);
    }
  },
  created() {
    this.$watch('innerValue', this.updateValue);
  }
};
</script>
<!-- ParentComponent.vue -->
<template>
  <div>
    <label>Parent Component:</label>
    <ChildComponent v-model="parentValue" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      parentValue: ''
    };
  }
};
</script>

在这个示例中,父组件中的 parentValue 通过 v-model 传递给了子组件,并且在子组件中通过 update:modelValue 事件更新。子组件内部使用 v-model 绑定了 innerValue,然后在内部监视器中监视 innerValue 的变化,并在变化时触发 update:modelValue 事件向父组件传递最新的值。

这种方式保持了 Vue.js 的单向数据流原则,并且使得组件之间的数据传递更加清晰和简洁。

求求赞助,没有那咱就加个友站或者点赞评论呗,多点交流
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇