Vue Sync Update

Posted on  by admin

Modified1 year, 7 months ago. I'm trying to use sync property pattern so that I can share a unique property between parent and child (so using a pattern like vuex seems unnecessary to me, like throwing a bomb at a fly).

I have managed to connect synchronous properties as follows:. This strategy has worked for me, it does what is expected of emitting the event of modifying the property from the child so that the parent updates it and the change is reflected in the child.

But my problem is that now the intention of the child to modify the property I want to do from a method and not directly.

This means (look @click line):. Child with method:. As you can see from the button I call the method that updates the property, which should call the $emit.

But with the method it doesn't but without the direct method it does. How could I do it with the method? 在说vue 修饰符sync前,我们先看下官方文档:vue .sync 修饰符,里面说vue .sync 修饰符以前存在于vue1.0版本里,但是在在 2.0 中移除了 .sync 。但是在 2.0 发布之后的实际应用中,我们发现 .sync 还是有其适用之处,比如在开发可复用的组件库时。我们需要做的只是让子组件改变父组件状态的代码更容易被区分。从 2.3.0 起我们重新引入了 .sync 修饰符,但是这次它只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 v-on 监听器。示例代码如下:.

当子组件需要更新 foo 的值时,它需要显式地触发一个更新事件:. vue 修饰符sync的功能是:当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中所绑定。如果我们不用.sync,我们想做上面的那个弹窗功能,我们也可以props传初始值,然后事件监听,实现起来也不算复杂。这里用sync实现,只是给大家提供一个思路,让其明白他的实现原理,可能有其它复杂的功能适用sync。. 这只是一个简单的例子,看完这个不知你是不觉得有个指令跟这个很相似,v-model?对,就是v-model在组件上使用的时候。具体的可以查看:vue 自定义组件使用v-model,可以实现同样的功能。也是以这个弹窗事件做演示的.

If you've got a Vue component that won't update the way you expect it to, this debugging guide will help you to quickly identify and fix the problem. Each section begins with a list of symptoms that you might be experiencing: This might apply to you if.

While not exhaustive, using this should help you find the relevant section pretty quickly.

Or if you want, you can also read this whole guide from beginning to end. The examples use the original options API instead of the newer composition API where possible.

This is because the composition API doesn't exist in Vue 2, and Vue 2 is still widely used. It's also a more advanced feature, and should only be used if you already understand the options API.

In a few places I also link to Vue documentation. These links go to the Vue 3 documentation, but most concepts are the same between versions, and you can also search the Vue 2 documentation if you need. Here are some links if you want to jump right in:. Before we get into it, you should first double check that you haven't made a silly mistake.

I know, I know, you've checked all of this stuff already.

But we all make these kinds of mistakes, and this step could save you a lot of time.

Make sure to check:. Typos: the variable you're updating, where you're using it, method names, computed prop names.