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'});
}
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/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:
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)
}
Related
I've tried many different ways to do this with both alert() and simple if-else statements, and even what is at this link: https://v2.vuejs.org/v2/cookbook/form-validation.html
But nothing works! What am I doing wrong?
What is in my index.html:
<div id="app">
<div class = "addTask">
<h1>A List of Tasks</h1>
<p v-show="activeItems.length === 0">You are done with all your tasks! Celebrate!</p>
<form #submit.prevent="addItem">
<input type="text" v-model="title">
<button type="submit">+</button>
</form>
</div>
This is what I have in scripts.js:
var app = new Vue({
el: '#app',
data () {
return {
// errors: [],
items: [{
userId: 0,
id: 0,
title: "",
completed: false,
}],
title: '',
show: 'all',
}
},
// Using axios to asynchrously query the API
mounted () {
axios
.get("https://jsonplaceholder.typicode.com/todos")
.then(response => this.items = response.data)
},
computed: {
activeItems() {
this.saveItems;
return this.items.filter(item => {
return !item.completed;
});
},
filteredItems() {
// An active state denotes the task is not yet completed
if (this.show === 'active')
return this.items.filter(item => {
return !item.completed;
});
if (this.show === 'completed')
return this.items.filter(item => {
return item.completed;
});
// This makes it so added tasks go to the top, not bottom
return this.items.reverse();
},
},
methods: {
addItem() {
if(this.items != 0) {
this.items.push({
title: this.title,
completed: false
})
this.title = "";
}
else {
alert("Please enter a task.")
}
Based on your code, you should declare a property called title in the data function and check if title is empty or not in addItem method.
var app = new Vue({
el: '#app',
data () {
return {
// errors: [],
title: '', // add this property in data function
items: [{
userId: 0,
id: 0,
title: "",
completed: false,
}],
title: '',
show: 'all',
}
},
// Using axios to asynchrously query the API
mounted () {
axios
.get("https://jsonplaceholder.typicode.com/todos")
.then(response => this.items = response.data)
},
computed: {
activeItems() {
this.saveItems;
return this.items.filter(item => {
return !item.completed;
});
},
filteredItems() {
// An active state denotes the task is not yet completed
if (this.show === 'active')
return this.items.filter(item => {
return !item.completed;
});
if (this.show === 'completed')
return this.items.filter(item => {
return item.completed;
});
// This makes it so added tasks go to the top, not bottom
return this.items.reverse();
},
},
methods: {
addItem() {
if(this.title !== '') { //check if `title` is empty or not
this.items.push({
title: this.title,
completed: false
})
this.title = "";
}
else {
alert("Please enter a task.")
}
I created an example in Stackblitz. You can also view the example directly by clicking here
Good afternoon everyone I'm having a problem converting json to csv, I'm using a lib I found at https://github.com/angeliquekom/vue-json-to-csv, to be very interesting, but I'm having trouble passing an arrau for component.
my code:
<template>
<vue-json-to-csv :json-data="data"
:labels="{
id: { title: 'id' },
co_tipo_nota: { title: 'co_tipo_nota' },
ds_nota: { title: 'ds_nota' },
ds_outro_criterio: { title: 'ds_outro_criterio' },
ds_nofl_avaliacao_anonimata: { title: 'fl_avaliacao_anonima' },
dt_nota: { title: 'dt_nota' },
}"
#success="val => handleSuccess(val)"
#error="val => handleError(val)">
<button>
<b>My custom button</b>
</button>
</vue-json-to-csv>
</template>
<script>
import VueJsonToCsv from 'vue-json-to-csv'
import { baseApiUrl } from '#/global'
import axios from 'axios'
export default {
name: 'DowloadCvsThree',
components: {
VueJsonToCsv,
},
data: function() {
return {
mode: 'save',
nota: {},
notas: [],
}
},
props: {
notas: Array
},
methods: {
loadUsers() {
const url = `${baseApiUrl}/notas`
axios.get(url).then(res => {
this.notas = res.data
})
},
mounted() {
this.loadUsers()
}
}
}
</script>
<style>
</style>
the error return is ?
[o erro][1]
[1]: https://i.stack.imgur.com/llHeZ.png
can anybody help me? I'm trying to pass an array to the json-to-csv: json-data = "data" component, but the date is not an array with I do?
he address of lib npm is: https://github.com/angeliquekom/vue-json-to-csv
awaiting return?
I'm having an undefined value when I put my object data inside the event.
Here are my codes:
data(){
return {
eventSources: [],
myId: 1
}
},
methods:{
myMethod(){
this.eventSources = [{
events(start,end,timezone,callback){
alert(this.myId);
axios.get(`/Something?id=${this.myId}`).then(response=>{
callback(response.data);
}).catch(error=>{console.log(error);});
}
}]
}
}
My alert is resulted to undefined but when I put my alert above the this.eventSources = [{...]] the alert has a value of 1
I hope somebody helps me.
The problem is this inside events() is not actually your Vue instance. You can fix the context by declaring events as an arrow-function:
this.eventSources = [{
events: (start,end,timezone,callback) => {
alert(this.myId);
}
}]
new Vue({
el: '#app',
data() {
return {
eventSources: [],
myId: 1
};
},
methods: {
myMethod() {
this.eventSources = [{
events: (start,end,timezone,callback) => {
alert(this.myId);
}
}]
this.eventSources[0].events(0, 1, 'UTC', data => console.log(data))
}
}
})
<script src="https://unpkg.com/vue#2.5.16"></script>
<div id="app">
<button #click="myMethod">Click</button>
</div>
I've got a question like in the title
How to stop mounting the component in <router-view> until receive a data from server or how to get the data before the component is mounted to <router-view>
My files:
1st main.js
new Vue({
el: '#app',
router,
components: { Login, Start },
data: function(){
return{
info: null,
}
},
methods:{
bef: function(){
this.$http.get('xxx').then(function(response){
return response.body
});
}
},
beforeMount(){
this.info= this.bef()
}
})
2nd component file Comp.vue
export default{
name: 'start',
data(){
return{
}
},
beforeMount(){
console.log(this.$parent.info)
}
}
how to do it properly to get not null value, but response from the server?
Thank you in advance
resolved with:
checkLogged: function() {
return new Promise((resolve,reject) => {
this.$http.get('xxx').then(response => {
if (response.body == 1) {
resolve(true);
} else {
resolve(false);
}
}, response => {
reject('connection failure');
});
});
},
and in 2nd file:
this.$root.checkLogged().then((response) => {
if(response){
this.logged = true
}else{
router.push("/")
}
})
I have an array:
basicForm.schema = [
{},
{} // I want to watch only this
]
I tried doing this:
‘basicForm.schema[1].value’: {
handler (schema) {
const plan = schema.find(field => {
return field.name === ‘plan’
})
},
deep: true
},
But I got this error:
vue.js?3de6:573 [Vue warn]: Failed watching path:
“basicForm.schema[1]” Watcher only accepts simple dot-delimited paths.
For full control, use a function instead.
What's the correct way of doing this?
You can watch a computed property instead:
new Vue({
el: '#app',
data: {
basicForm: {
schema: [
{a: 1},{b: 2} // I want to watch only this
]
}
},
computed: {
bToWatch: function() {
return this.basicForm.schema[1].b
}
},
methods: {
incB: function() {
this.basicForm.schema[1].b++
}
},
watch: {
bToWatch: function(newVal, oldVal) {
console.log(newVal)
}
}
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<button #click="incB()">Inc</button>
</div>
You should use a function as the warning message suggests. You need to do so via vm.$watch.
new Vue({
el: '#app',
data: {
items: [
{ name: 'bob' },
{ name: 'fred' },
{ name: 'sue' },
],
},
created() {
this.$watch(() => this.items[1].name, this.onNameChanged);
},
methods: {
changeValue() {
this.items[1].name = 'rose';
},
onNameChanged(name) {
alert('name changed to ' + name);
},
},
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<button #click="changeValue">Click me</button>
</div>
You should probably check that this.items[1] exists before accessing it inside the watch function otherwise you'll get an error.