[英]Vue.js - how to have multiple inputs in a component
I have just started learning Vue.js and I am trying to get the values from my components. 我刚刚开始学习Vue.js,并且试图从组件中获取值。 Is there a way to have multiple input fields in my component and get the value of each outside of the component? 有没有一种方法可以在我的组件中具有多个输入字段并获取组件外部的每个值?
For example, if I wanted to get and change the value for both of my input fields in my simple-input component. 例如,如果我想获取并更改我的简单输入组件中两个输入字段的值。 Right now they both have the same value but I would like to have 2 different values in each input. 现在它们都具有相同的值,但我想在每个输入中具有2个不同的值。
My component 我的组件
Vue.component('simple-input', {
template: `
<div>
<input type="text" :value="value" @input="$emit('input', $event.target.value)">
<input type="text" :value="value" @input="$emit('input', $event.target.value)">
</div>
`,
props: ['value']
});
main.js main.js
new Vue({
el: '#root',
data: {
value1: 'Initial value 1',
value2: 'Initial value 2',
value3: 'Initial value 3'
},
methods: {
alertSimpleInput1() {
alert(this.value1);
this.value1 = 'new';
}
}
});
HTML HTML
<simple-input v-model="value1"></simple-input>
<simple-input v-model="value2"></simple-input>
<simple-input v-model="value3"></simple-input>
<button @click="alertSimpleInput1">Show first input</button>
if you want to have different values for each input you have two choices: 如果您希望每个输入具有不同的值,则有两个选择:
first implementation: 第一次执行:
Vue.component('simple-input', { template: ` <div> <input type="text" :value="value1" @input="$emit('input', $event.target.value)"> <input type="text" :value="value2" @input="$emit('input', $event.target.value)"> </div> `, props: ['value1','value2'] }); new Vue({ el: '#root', data: { value11: 'Initial value 11', value12: 'Initial value 12', value21: 'Initial value 21', value22: 'Initial value 22', value31: 'Initial value 31', value32: 'Initial value 32' }, methods: { alertSimpleInput1() { alert(this.value11); this.value11 = 'new'; } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="root"> <simple-input :value1="value11" :value2="value12"></simple-input> <simple-input :value1="value21" :value2="value22"></simple-input> <simple-input :value1="value31" :value2="value32"></simple-input> <button @click="alertSimpleInput1">Show first input</button> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.