Reputation: 1539
I have a form
which is have hidden input. There is a small list of my data. Just has title
and id
. This list created by vue component. I want to click this list items then change to hidden input value. Here is my structure.
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>",
});
This is my codes.
Upvotes: 0
Views: 8176
Reputation: 82459
Add an event handler.
<account-select @account-change="onAccountChange" :datalist="{{ json_encode($list) }}"></account-select>
In your parent Vue add
methods:{
onAccountChange(id){
this.account_id = id
}
}
And update your component to
methods: {
item_id_bind(id) {
this.$emit("account_change", id)
}
},
Here is a working example.
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/[email protected]/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>
Upvotes: 1