我刚开始学习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 ...”。您需要将输入的值绑定到组件上的数据属性。使用v-model
进行双向绑定(输入值更改时,它将更新data属性的值,反之亦然)。
在您的示例中,实际上涉及的内容更多,因为您要从根组件获取输入的值,因此<simple-input>
组件必须公开此内容。做到这一点的方法是使用道具(用于父级到子级数据流)和事件(用于子级到父级数据流)。
未经测试:
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>
代码的说明)