繁体   English   中英

Vue.js - 如何获取和设置组件输入字段的值?

[英]Vue.js - How to get and set a value of a component input field?

我刚开始学习 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进行双向绑定(当输入值发生变化时,它会更新数据属性的值,反之亦然)。

在您的示例中,实际上涉及更多,因为您想从根组件获取输入的值,因此<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,但是对于初学者来说,这里有很多东西要解开。 我不会详细介绍,因为已经有很多关于这些概念的信息。

阅读以下:

为此,您可以使用 $emit 方法。

<simple-input @clicked="inputValue" :name="name"></simple-input>

parent methods

export default {

 data: function () {
    return {
       name:null
    }
  },
  methods: {
   inputValue (value) {
    console.log(value) // get input value
   }
 }
}
  Vue.component('simple-input', {
  data: function () {
    return {
       // name:null
    }
  },
  watch:{
    'name':function(){
        this.$emit('clicked', this.name)
    }
   template: '<input type="text" v-model="name">'
   props:['name']
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM