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

时间:2017-11-06 11:31:45

标签: vuejs2 vue-component

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

2 个答案:

答案 0 :(得分: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结构,我没有这么想;当我六个月后回来改变一些事情时,我更容易理解我在做什么。)

答案 1 :(得分:0)

您的问题:

  

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

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

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

  

道具功能是否可以替代v-model?

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

我建议你阅读official documentation ...

相关问题