[英]Vue.js .$set is not a function
I'm trying to modify the data that stored in vuejs by using $set
function.我正在尝试使用$set
函数修改存储在 vuejs 中的数据。 But I got this error: TypeError: app.messageBox.$set is not a function.
但是我收到了这个错误: TypeError: app.messageBox.$set is not a function.
Here is the code about how I define app and messageBox:下面是关于我如何定义 app 和 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:在另一个js文件中,我尝试修改messageBox中的数据:
function test() {
app.messageBox.$set(0, {message: 'aaa'});
}
The correct syntax is Vue.set(target, index, value)
.正确的语法是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)
:在组件代码或单文件组件中使用时,您可以使用等效别名: 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/vue@2.6.10/dist/vue.min.js"></script> <div id="app"> <p v-for="msgBox of messageBox">{{msgBox.message}}</p> </div>
This example is for update the qty of product in the array car:此示例用于更新数组 car 中的产品数量:
const indice = this.car.findIndex((pr) => pr.id === product.id);
if(indice===-1){
product.qty = 1
this.car.push(product)
}else{
//Vue no detectara cambios en el array si se actualiza por indice https://stackoverflow.com/a/59289650/16988223
//this.car[indice].qty++
const productUpdated = product
productUpdated.qty++
this.$set(this.car, indice, productUpdated)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.