美文网首页让前端飞Web前端之路
Vue two-way binding between pare

Vue two-way binding between pare

作者: 柳正来 | 来源:发表于2020-03-29 02:16 被阅读0次

    In Vue, the most commonly used two-way binding is v-model.

    For example, you can do the following to have a two-way binding on a text input.

    <input type="text" v-model="userInput" />
    

    The value of userInput will be shown in the text input, and the user's input into the control will update the userInput.

    Then how to write a two-way binding for my own component?

    Here I want to implement a Setting component which contains a checkbox for a setting, say, "Mirror".

    Don't directly mutate a prop

    You can't do the following because mirror is passed in as a prop and you shouldn't mutate it.

    <input type="checkbox" v-model="mirror" />
    

    Otherwise you'll get the following warning.

    Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "mirror"

    .sync Modifier

    Then what's the right way to do it? You can get some idea by reading .sync modifier

    In Vue, it's recommended to emit events in the pattern of update:myPropName.

    this.$emit('update:title', newTitle)
    

    Then the parent can listen to that event and update a local data property.

    <text-document
      v-bind:title="doc.title"
      v-on:update:title="doc.title = $event"
    ></text-document>
    

    For convenience, they offer a shorthand for this pattern with the .sync modifier:

    <text-document v-bind:title.sync="doc.title"></text-document>
    

    Example

    Now back to our example. In the parent component we can simply add .sync modifier to the mirror binding.

    <!-- parent component -->
    <setting :mirror.sync="mirror" />
    

    And in the child component, instead of using v-model, we need to use two bindings -- one for reading value, another for writing value.

    As for checkbox, reading the value is done with checked binding. And writing the value is done by the change event.

    <!-- setting component -->
    <input type="checkbox" :checked="mirror" @change="$emit('update:mirror', $event.target.checked)"
    

    For how to read and write value in other form controls, you can read this.

    相关文章

      网友评论

        本文标题:Vue two-way binding between pare

        本文链接:https://www.haomeiwen.com/subject/datyuhtx.html