什么时候应该使用键与v模型进行输入?

时间:2019-07-14 10:16:55

标签: javascript html vue.js

我是vue.js的新手,在Conditional Rendering documentation的本节中偶然发现,介绍了vue如何尝试重用尽可能多的组件。在该示例中,使用了一个输入,如果您仅想覆盖对象的不同属性,则直接输入。如果您希望交换整个元素,则可以使用key属性。

在输入元素上使用key="whatever"很好,但是当我使用v-model="myAnswer"时,它在文档中的示例中具有相同的效果。

let data = {happy: true, why: '', whyN: ''}

let standart = new Vue({
  el: '#standart',
  data: data
});

let withKey = new Vue({
  el: '#withKey',
  data: data
});

let withModel = new Vue({
  el: '#withModel',
  data: data
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="standart">
  <i>Without anything</i>
  <template v-if="happy">
    <label>Why are you happy?</label>
    <input placeholder="Because it's cool">
  </template>
  <template v-else>
  <label>Why are you unhappy?</label>
  <input placeholder="It's to slow">
  </template>
  <button @click="happy = !happy">Toggle</button>
</div>

<hr>
<div id="withKey">
  <i>With key</i>
  <template v-if="happy">
    <label>Why are you happy?</label>
    <input placeholder="Because it's cool" key="happy">
  </template>
  <template v-else>
  <label>Why are you unhappy?</label>
  <input placeholder="It's to slow" key="unhappy">
  </template>
  <button @click="happy = !happy">Toggle</button>
</div>

<hr>
<div id="withModel">
  <i>With model</i>
  <template v-if="happy">
    <label>Why are you happy?</label>
    <input placeholder="Because it's cool" v-model="why">
  </template>
  <template v-else>
  <label>Why are you unhappy?</label>
  <input placeholder="It's to slow" v-model="whyN">
  </template>
  <button @click="happy = !happy">Toggle</button>
</div>

我想知道这些功能的比较方式,何时使用以及总体上它们各自的优点是什么。对我来说,文档并不能很好地解释。

1 个答案:

答案 0 :(得分:0)

好吧,通常您需要列表中的密钥,并且密钥必须来自某个来源,以使给定条目的密钥不会随时间变化。 如果使用UUID生成器,则密钥将在每次重新渲染时更改,并且您不希望这样做。因此,最好的解决方案是使用json-server之类的东西来模拟事物或使用真正的后端api。

在类似OAuth2的情况下,默认情况下,由于协议要求使用www-form-urlencoded,因此您无法发送内容类型为application / json的POST对象以及主体对象中的数据。

在这种情况下,您需要类似

<form ref="someForm">
  <input name="nameofinput" ref="myFancyInput" />
</form>
通过访问this。$ refs

,您可以执行以下操作:

this.$refs["myFancyInput"]="somevalue"
this.$refs["someForm"].submit();

输入值的内容也可以是JSON,因为JSON只是以给定方式格式化的字符串。

然后在后端,您可以根据需要进行处理。

http://www.davidepugliese.com/csv-download-ajax-and-spring/

对于v模型注释,这只是诸如此类的快捷方式:

<input :value="someVar" @input="functionName($event)" />


functionName(event) {
   console.log(event)

}
相关问题