我刚刚开始学习 Vue.js,但遇到了一个问题,我不知道如何访问和更改组件内的文本字段值。
假设我想访问或更改组件内第一个输入字段的值
我的组件
Vue.component('simple-input',
{
template: `
<input type="text" value="Some value...">
`,
});
HTML
<div id="root">
<simple-input></simple-input>
<simple-input></simple-input>
<simple-input></simple-input>
<div @click="alertSimpleInput1">Show first input value</div>
<div @click="changeInput1('new value')">Change input value</div>
<div @click="alertSimpleInput2">Show second input value</div>
</div>
main.js
new Vue({
el: '#root',
});
最佳答案
有value="Some value..."
在模板中意味着输入的值最初将设置为字符串“Some value...”。您需要将输入的值绑定(bind)到组件上的数据属性。使用 v-model
对于双向绑定(bind)(当输入值更改时,它将更新 data 属性的值,反之亦然)。
在您的示例中,实际上涉及更多一点,因为您想从根组件获取输入的值,因此 <simple-input>
组件必须公开它;实现此目的的方法是使用 props (用于父到子数据流)和 events (用于子到父数据流)。
未经测试:
Vue.component('simple-input', {
template: `
<input type="text" :value="value" @input="$emit('input', $event.target.value)">
`,
props: ['value'],
});
<div id="root">
<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 value</button>
<button @click="changeInput1('new value')">Change input value</button>
<button @click="alertSimpleInput2">Show second input value</button>
</div>
new Vue({
el: '#root',
data: {
value1: 'Initial value 1',
value2: 'Initial value 2',
value3: 'Initial value 3',
},
methods: {
alertSimpleInput1() {
alert(this.value1);
},
alertSimpleInput2() {
alert(this.value2);
},
changeInput1(newValue) {
this.value1 = newValue;
},
},
});
我知道您刚刚学习 Vue,但是对于初学者来说,这里还有很多东西需要解开。我不会详细介绍,因为已经有很多关于这些概念的信息。
阅读以下内容:
- Component Basics
- Using
v-model
on Components (了解<simple-input>
代码的解释)
关于javascript - Vue.js - 如何获取和设置组件输入字段的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53666296/