在Vuejs中同步道具 [英] Synchronise a props in Vuejs
问题描述
我正在尝试在 vue.js 。
我有一个包含带有prop的子组件的父组件。当父级中的道具发生变化时,道具在孩子中更新,当道具中的道具发生变化时,父级会更新。
I have a parent component that includes a child component with a prop. When the prop changes in the parent, the prop is updated in the child and when the prop changes in the child, the parent is updated.
我从这个例子开始:
装载我的组件的html
The html where my component is mounted
<div>
<div id="app">
</div>
</div>
父母+子女:
Vue.component('myinput', {
template: '<div><input v-model="mytext" /></div>',
props: ['text'],
data() {
return {
mytext: this.text
}
}
})
const vm = new Vue({
el: '#app',
template: '<div> <myinput :text="mytext"></myinput> <p> {{mytext}} </p></div>',
data() {
return {
mytext: "Hello World!"
}
}
});
由于我不能改变道具,我需要一个本地副本 [示例代码集] 。
Since I cannot mutate the props, I need a local copy [Example Codepen].
如果我想要我的父母当孩子改变时要更新的组件,我需要 $ emit
该值。
If I want my parent component to be updated when the child change, I need to $emit
the value.
为此,我创建了子组件中 mytext
的包装:
For that, I created a wrapper around mytext
in the child component:
computed: {
wrapperMyText: {
get() {
return this.mytext;
},
set(v) {
this.mytext = v;
this.$emit('update:text', v);
}
}
我在模型中使用了wrapperMyText。 [Codepen]示例
I use wrapperMyText in the model. [Example Codepen]
现在,如果我想要另一种方式绑定(父对子)我需要在孩子中添加一个观察者。
Now, if I want the binding the other way (parent to child) I need to add a watcher in the child.
watch: {
text(v) {
this.mytext = v;
}
},
在示例中,有只有一个道具,我需要创建一个观察者和一个计算属性。如果我有5个属性,我将需要5个观察者和5个计算属性。这意味着组件代码被所有这些东西污染了(代码太多)。所以我的问题是:
In the example, there is only one prop, I need to create a watcher and a computed property. If I have 5 properties, I will need 5 watchers and 5 computed properties. That means the component code is polluted (too much code) with all this stuff. So my questions are:
这是同步道具的标准模式吗?
在这种情况下使用商店是否更好(如vuex )?
为什么需要这么多代码来做一个简单的案例?
Is this the standard pattern to sync a prop?
Is it better in this case to use a Store (like vuex)?
Why is so much code necessary to do a simple case?
经过反思,似乎我正在尝试用属性重新编码v-model。
After reflection, it seems I'm trying to re code v-model with properties.
推荐答案
单个计算属性将完成您尝试的所有事情。
A single computed property will accomplish everything you are attempting.
Vue.component('myinput', {
template: '<div><input v-model="wrapperMyText"></div>',
props: ['text'],
computed: {
wrapperMyText: {
get() { return this.text;},
set(v) { this.$emit('update:text', v);}
}
}
})
这是您的更新的笔。
所以回答你的问题:
- 这是标准模式。
- 如果您将状态置于Vuex中,您的输入组件将不再可重复使用。
- 您不需要所有代码。
这篇关于在Vuejs中同步道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!