【问题标题】:vuejs how do I change input value from componentsvuejs如何更改组件的输入值
【发布时间】:2025-11-23 03:55:01
【问题描述】:

我有一个form,它有隐藏的输入。我的数据有一个小列表。只有titleid。此列表由 vue 组件创建。我想单击此列表项,然后更改为隐藏的输入值。这是我的结构。

HTML

<div id="v-account-select">
  <form method="post">
    {!! csrf_field() !!}
    <input type="hidden" name="id" v-model="account_id">
  </form>
  <account-select :datalist="{{ json_encode($list) }}"></account-select>
</div>

APP.JS

Vue.component("account-select", {
  datalist: {
    type: Array,
    required: true,
  },
  methods: {
    item_id_bind(id) {
      this.$emit("#account_id", id);
    },
  },
  template:
    '<table class="table table-responsive table-striped table-bordered">' +
    "<tbody>" +
    '<tr v-for="item in datalist"><td>' +
    '<button type="button" class="btn-link" v-on:click="item_id_bind(item.id)">{{item.title}}</button>' +
    "</td></tr>" +
    "</tbody>" +
    "</table>",
});

这是我的代码。

【问题讨论】:

    标签: javascript vuejs2 vue-component buttonclick


    【解决方案1】:

    添加事件处理程序。

    <account-select @account-change="onAccountChange" :datalist="{{ json_encode($list) }}"></account-select>
    

    在你的父级 Vue 中添加

    methods:{
        onAccountChange(id){
            this.account_id = id
        }
    }
    

    并将您的组件更新为

    methods: {
        item_id_bind(id) {
            this.$emit("account_change", id)
        }
    },
    

    这是一个工作示例。

    console.clear()
    
    Vue.component('account-select', {
      props: {
        datalist: {
          type: Array,
          required: true
        }
      },
      methods: {
        item_id_bind(id) {
          this.$emit("account-change", id)
        }
      },
      template:`
        <table class="table table-responsive table-striped table-bordered">
          <tbody>
            <tr v-for="item in datalist" :key="item.id">
              <td>
                <button type="button" 
                        class="btn-link" 
                        v-on:click="item_id_bind(item.id)">
                  {{item.title}}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      `
    });
    
    
    new Vue({
      el: "#app",
      data: {
        datalist: [{
          id: 1,
          title: "item1"
        }, {
          id: 2,
          title: "item2"
        }],
        account_id: null
      },
      methods: {
        onAccountChange(id) {
          this.account_id = id
        }
      }
    })
    <script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
    <div id="app">
      <div id="v-account-select">
    
        <form method="post">
          Current Account id: {{account_id}}
          <input type="hidden" name="id" v-model="account_id">
        </form>
        <account-select @account-change="onAccountChange" :datalist="datalist"></account-select>
      </div>
    </div>

    【讨论】:

    • 是的,这是我的解决方案。对不起,我有点复杂。感谢您的帮助。
    最近更新 更多