Reputation: 103
I have a jquery click function on a table row that takes the value of the table row and puts it into a list i then set the list equal to the vue array i have here are the arrays. Array:
tableRow: [
{
"name": "1",
"numSongs": "2",
"Year": "3"
}
]
Function:
$("#table1 tr").click(function () {
var list = [];
var $row = $(this).closest("tr"),
$tds = $row.find("td");
list.push({ name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() });
this.tableRow = list;
console.log(this.tableRow);
});
I also log the value of the list when the app loads and when i click it and it does change.
Then i have a function to test if the values have changed just a simple alert function.
greet: function () {
// `this` inside methods points to the Vue instance
alert('Hello ' + this.tableRow[0].name )
},
But the value doesn't update in the function does anyone know why.
Vue Instance Code
export default {
data() {
return {
tableRow: [
{
"name": "1",
"numSongs": "2",
"Year": "3"
}
]
}
},
mounted: function () {
console.log(this.tableRow);
this.$nextTick(() => {
$("#table1 tr").click(function () {
var list = [];
var $row = $(this).closest("tr"),
$tds = $row.find("td");
list.push({ name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() });
this.tableRow = list;
console.log(this.tableRow);
});
});
},
methods: {
greet: function () {
// `this` inside methods points to the Vue instance
alert('Hello ' + this.tableRow[0].name )
},
}
}
Upvotes: 0
Views: 3855
Reputation: 31352
This is due to the scoping issue of this
In your click handler you are doing this.tableRow = list
where tableRow
is a property of data option in the vue instance but this
is not pointing to the vue instance, it refers to element which invoked the event
So do it like this:
mounted: function () {
var self = this;
console.log(this.tableRow);
this.$nextTick(() => {
$("#table1 tr").click(function () {
var list = [];
var $row = $(this).closest("tr"),
$tds = $row.find("td");
list.push({ name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() });
self.tableRow = list;
console.log(this.tableRow);
});
});
},
Upvotes: 3