javascript - 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
组件我想改变msg
App.vue的数据中的组件。但是当我更改值时,Vue 会发出警告:
所以我不明白下一步该怎么做。请帮助我。
解决方案
一种简单的解决方案是使用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 推荐的
推荐阅读
- android - Android用意图填充谷歌日历附件字段
- python - 如何使用值更新 many2many 列表 [ODOO 12]
- android - 取货地点预测列表
- python - 当我使用 input() 要求用户输入时,为什么会出现 NameError?
- javascript - 如何在节点 js 中将 TCP 套接字数据包发送到网页
- julia - 在 Julia 中解决 DDE 的问题
- python - 如何在 Pandas 中将具有 Null 值的浮点数据类型转换为整数?
- javascript - 将值/变量从 HTML 传递到 JS 文件
- python - 如何在我的脚本中添加这个 url 而不会使用 selenium python 中断当前循环
- javascript - 尝试列出数据库 postgres TypeError [ERR_INVALID_ARG_TYPE] 的表时收到错误