首页 > 解决方案 > Vue中双向绑定props的正确方式是什么?

问题描述

这里我有两个组件:

消息.vue

<template>
 <div>
   <input type="text" v-model="msg" />
 </div>
</template>
<script>
export default {
 name: "msg",
 props: ["msg"]
};
</script>

样本.vue

<template>
  <div>
    <h2>{{ msg }}</h2>
  </div>
</template>
<script>
export default {
  name: "samples",
  props: ["msg"]
};
</script>

最后,

应用程序.vue

<template>
  <div id="app">
    <samples v-bind:msg="msg"></samples>
    <msg :msg="msg"></msg>
  </div>
</template>

<script>
import samples from "./components/samples.vue";
import msg from "./components/msg.vue";
export default {
  name: "app",
  components: {
    samples,
    msg
  },
  data: () => {
    return {
      msg: "Hello World"
    };
  }
};
</script>

<style>
#app {
  font-family: "Poppins", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  margin-top: 60px;
}
</style>

我想做的事情是用msg组件我想改变msgApp.vue的数据中的组件。但是当我更改值时,Vue 会发出警告:

Vue 错误

所以我不明白下一步该怎么做。请帮助我。

标签: javascripthtmlcssvue-componentvuejs3

解决方案


一种简单的解决方案是使用v-bind.sync。按照链接查看文档和用法。通过使用它,您需要从您的代码中更改 2 行代码以使其工作:

App.vue 中

change
<msg :msg="msg"></msg>
to
<msg :msg.sync="msg"></msg>

msg.vue 中

change
<input type="text" v-model="msg" />
to
<input type="text" @input="$emit('update:msg',$event.target.value)" />

但是,这个不是 Vue 推荐的


推荐阅读