Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-7
rated 0 times [  0] [ 7]  / answers: 1 / hits: 16954  / 7 Years ago, thu, october 19, 2017, 12:00:00

I'm trying to modify the data that stored in vuejs by using $set function. But I got this error: TypeError: app.messageBox.$set is not a function.



Here is the code about how I define app and messageBox:



app = new Vue({
el: '#app',
data: {
messageBox: [{
id: 1,
message: 'first'
}, {
id: 2,
message: 'second'
}]
}
});


and in another js file, I try to modify the data in messageBox:



function test() {
app.messageBox.$set(0, {message: 'aaa'});
}

More From » vue.js

 Answers
10

The correct syntax is Vue.set(target, index, value).
When used inside component code or single-file-components, you could use the equivalent alias: this.$set(target, index, value):


Vue.set(app.messageBox, 0, { message: 'outside component' });

// or when you don't access to `Vue`:
app.$set(app.messageBox, 0, { message: 'outside component' });

// or when `this` is the Vue instance:
this.$set(this.messageBox, 0, { message: 'inside component' })



const app = new Vue({
el: '#app',
data() {
return {
messageBox: [{
id: 1,
message: 'first'
}, {
id: 2,
message: 'second'
}]
};
},
mounted() {
setTimeout(() => {
this.$set(this.messageBox, 0, { message: 'inside component' })
}, 1000)
}
});

setTimeout(() => {
Vue.set(app.messageBox, 0, { message: 'outside component' });
}, 2000);

<script src=https://unpkg.com/[email protected]/dist/vue.min.js></script>

<div id=app>
<p v-for=msgBox of messageBox>{{msgBox.message}}</p>
</div>




[#56187] Monday, October 16, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ernest

Total Points: 332
Total Questions: 92
Total Answers: 98

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
;