首页 文章

v-model vs自定义Vue组件的道具

提问于
浏览
0

Vue中的v-model是一个内置功能,仅适用于少数选定的标签?道具功能是否是v-model的替代品?

2 回答

  • 4

    Vue中的v-model是一个内置功能,仅适用于少数选定的标签?

    v-model 是一个directive,默认情况下适用于表单元素,但您也可以在自己的组件中使用它 . 它实际上只是一个接受名为"value"的属性并发出名为"input"的事件的组件的简写 .

    这是使用v-model的任意组件的样板:

    <template>
      <div>
        My value is {{displayValue}}
        <button @click="go">Change it</button>
      </div>
    </template>
    <script>
    export default {
      name: 'exampleComponent',
      props: ['value'],
      data() {
        return {displayValue: ''}
      },
      mounted() {
        this.displayValue = this.value; // initialize internal variables
      },
      watch: {
        value() {
          // Parent property changed; update internal variables
          this.displayValue = this.value;
        }
      },
      methods: {
        go() {
          // example change handler
          this.$emit('input', "NEW VALUE"); // tell the parent to update to the new value. This will update via the watch:value()
        }
      }
    };
    </script>
    

    然后,父组件可以像任何其他表单元素一样执行 <example-component v-model="someVariable"></example-component> .

    道具功能是v-model的替代品?

    只有一半 . 道具是一种将值传递给子组件的方法,但是它们本身并没有为您提供一种方法来将该值的更改传达回父组件;为此,您需要 $emit 更改的值 .

    (你也可以完美地做到这一点,没有 v-model ,当然,使用你自己的命名道具和发射,但我发现如果我坚持 v-model 结构,我不会更容易理解我在做什么 . )

  • 0

    你的问题:

    Vue中的v-model是一个内置功能,仅适用于少数选定的标签?

    是的, v-model 适用于用户可以交互或修改数据的所有标签: input, textarea, radio, select ...

    您可以将 v-model 用于自定义HTML的内置输入类型 . Vue组件允许您使用完全自定义的行为构建可重用输入 . 查看更多here

    道具功能是否是v-model的替代品?

    不, props 是父组件与其子组件共享数据的方式, v-model 是同一组件,表单或用户输入中的数据绑定(双向数据绑定)...

    我建议你阅读official documentation ...

相关问题