我有一个带有隐藏输入的表单
。我的数据有一个小列表。只有 title
和 id
。该列表由 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>",
});
这是我的代码。
最佳答案
添加事件处理程序。
<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>
关于javascript - vuejs 如何更改组件的输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44574149/