Vue2: Avoid mutating a prop directly inside component - javascript

I'm gettig this "Avoid mutating a prop directly", when checking if the persons input should get an invalid class because its empty.
<script type="text/x-template" id="srx">
<input type="number" name="persons" id="persons" value="" v-model="persons" :class="{invalid: !persons}">
</script>
<div id="app">
{{stepText}}
<sr-el :persons="1"></sr-el>
<button v-if="currentStep > 1" type="button" v-on:click="previous()">prev</button>
<button v-if="currentStep < 6" type="button" :disabled="currentStepIsValid()" v-on:click="next()">
next</button>
</div>
Vue.component('sr-el', {
template: '#srx',
props: ['persons'],
})
var App = window.App = new Vue({
el: '#app',
data: {
persons: '1'
currentStep: 1,
},
methods: {
currentStepIsValid: function() {
if (this.currentStep == 1) {
this.stepText = "Step 1;
return !(this.persons > 0);
}
},
previous: function() {
this.currentStep = this.currentStep - 1;
// prev slide
},
next: function() {
this.currentStep = this.currentStep + 1;
// next slide
}
}
})

You're getting that warning because you are binding persons to the input in the template via v-model. Changing the input's value will thus change the value of persons, which means the prop is getting mutated directly in your sr-el component.
You should set a new property equal to persons and pass that to v-model instead:
Vue.component('sr-el', {
template: '#srx',
props: ['persons'],
data: function() {
return {
inputVal: this.persons,
}
}
})
<input v-model="inputVal" ... />

Related

Vue how do you select all the text in a component with a computed property

I can normally select all the text with $event.target.select() but in this case I think it is selecting all and then replacing the selection with the computed property. How do you select all after the computed property is finished?
Vue.component('my-component', {
template: `
<div>
My Component
<input type="text" v-model="displayValue" #blur='isInputActive = false' #focus='isInputActive = true;$event.target.select()'></input>
</div>
`,
props:['value'],
data() {
return {
isInputActive: false
};
},
computed: {
displayValue: {
get: function() {
return (this.isInputActive) ? this.value : this.value.toUpperCase();
},
set: function(val) {
this.$emit('input', val);
},
}
},
})
new Vue({
el: '#app',
data() {
return {
test: "Test"
};
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<my-component v-model="test"></my-component>
</div>
You can use the $nextTick which run the callback after the computed property is finished.
#focus='isInputActive = true; $nextTick(() => $event.target.select())'

How to calculate the sum of values of dynamically created input?

Background- I have created an app where the parent component can create and delete a input field (child component) on a click of a button. The input's value is recorded on screen through v-model
Problem- When a new input is created the previous value is replaced by the new input value.
Expectation- When a new input is created it adds the value of the previous input value
A visual for more clarity
https://i.stack.imgur.com/Fp8Mk.png
Parent Component
<form-input v-for="n in count" :key="n" :value="expense" #input="expense = $event"></form-input>
<button #click="addInputs">Add Expense</button>
<button #click="deleteInputs">Delete</button>
<p>Total Expense: {{ expense }}</p>
export default {
components: {
"form-input": formInput
},
name: "form",
data() {
return {
count: 0,
expense: 0
};
},
methods: {
addInputs: function() {
this.count++;
},
deleteInputs: function() {
this.count--;
}
}
};
Child Component
<input type="text" placeholder="Expense" />
<input type="number" placeholder="Amount" #input="$emit('input', $event.target.value)" />
Here, I made a sandbox for you to see my solution for this as there are a lot of changes and you can see how it performs.
https://codesandbox.io/s/confident-fire-kpwpp
The main points are:
You have to keep track of the values of each input separately. This is done using an array.
When this array is changed we recalculate the total expense
Parent
<template>
<div>
<form-input v-for="(n, idx) in count" :key="n" :id="idx" #input="getExpense"></form-input>
<button #click="addInputs">Add Expense</button>
<button #click="deleteInputs">Delete</button>
<p>Total Expense: {{ totalExpense }}</p>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
components: {
"form-input": HelloWorld
},
name: "form",
data() {
return {
count: 0,
expenses: [],
totalExpense: 0
};
},
methods: {
addInputs: function() {
this.count++;
this.expenses[this.count - 1] = 0;
},
deleteInputs: function() {
this.count--;
this.expenses.pop();
this.setTotalExpense();
},
getExpense(data) {
this.expenses[data.id] = parseInt(data.value, 10) || 0;
this.setTotalExpense();
},
setTotalExpense() {
console.log(this.expenses);
this.totalExpense = this.expenses.reduce((sum, val) => {
return sum + val;
}, 0);
}
}
};
</script>
Child
<template>
<div class="hello">
<input type="text" placeholder="Expense">
<input
type="number"
placeholder="Amount"
#input="$emit('input', {
value: $event.target.value,
id
})"
>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
id: Number
}
};
</script>
I used the HelloWorld template so that's why there are some references to that, but I'm sure you can easily clean that up :)
And also, there may be some small edge case bugs that you can clean up. This should point you in the right direction though.

How to track changed Valued from array of objects in vuejs

I have an addRows array which contains a group of objects.
These objects are added dynamically when using click + button.
Then they are pushed to the addRows array; after that, the user fills these objects.
Every object has many input values such as price and quantity.
I need to change the price when the quantity changes, but the problem is if the value was added before, the returned changed item is empty.
This happens because the new value was added before in the old values array.
As shown in the image third value same first so the array returned empty value of third item
I tried foreach and for also map but I'm facing the same problem.
computed: {
originalDistValue(a , b) {
return this.addRows.map(i => {
return i.dist
})
}
}, // close computed
watch: {
originalDistValue(a , b) {
let newVal = a.filter( obj => {
return b.indexOf(obj) == -1;
})
let element = this.addRows.filter( i => {
return i.dist == newVal;
})
deep: true
console.log(newVal)
for(let i in element) {
element[i].cit = 1;
}
}
}
At first create a child component for each row
Pass each row to component
Handle the single object inside the component instead of handling an array of objects in parent
See this example:
Vue.component('child', {
props: {
value: { type: Object, default: () => ({}) }
},
data: function() {
return {
selfValue: null
}
},
watch: {
value: {
handler(value) {
this.selfValue = value
},
immediate: true,
deep: true
},
selfVaue: {
handler(value) {
// you can also validate value then emit it
this.$emit('input', value)
},
deep: true
},
'selfValue.quantity'() {
this.selfValue.price = 0
}
},
template: `
<div class="d-flex justify-content-between">
<label>
Title:
<input type="text" v-model="selfValue.title" class="form-control" />
</label>
<label>
Quantity:
<select v-model="selfValue.quantity" class="form-control">
<option value="A">A</option>
<option value="B">B</option>
</select>
</label>
<label>
Price:
<input type="tel" v-model="selfValue.price" class="form-control" />
</label>
</div>
`
})
new Vue({
el: '#app',
data: {
rows: []
},
methods: {
add() {
this.rows.push({ title: '', quantity: '', price: 0 })
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div id="app" class="container">
<h2 class="mb-3">Rows:</h2>
<div v-for="row,i in rows">
<child v-model="row"></child>
<hr class="mt-1 mb-1" />
</div>
<button #click="add" class="mb-3">
ADD
</button>
<pre>{{ rows }}</pre>
</div>

Click-and-edit text input with Vue

I'm looking for a click-and-edit Vue component.
I've found a fiddle and made some edits. It works like this:
The fiddle is here.
The problem: I need an additional click to make the input focused. How can I make it focused automatically?
The code from the fiddle. HTML:
<div id="app">
Click the values to edit!
<ul class="todo-list">
<li v-for = "todo in todos">
<input v-if = "todo.edit" v-model = "todo.title"
#blur= "todo.edit = false; $emit('update')"
#keyup.enter = "todo.edit=false; $emit('update')">
<div v-else>
<label #click = "todo.edit = true;"> {{todo.title}} </label>
</div>
</li>
</ul>
</div>
JS:
new Vue({
el: '#app',
data: {
todos: [{'title':'one value','edit':false},
{'title':'one value','edit':false},
{'title':'otro titulo','edit':false}],
editedTodo: null,
message: 'Hello Vue.js!'
},
methods: {
editTodo: function(todo) {
this.editedTodo = todo;
},
}
})
You can use a directive, for example
JS
new Vue({
el: '#app',
data: {
todos: [
{ title: 'one value', edit: false },
{ title: 'one value', edit: false },
{ title: 'otro titulo', edit: false }
],
editedTodo: null,
message: 'Hello Vue.js!'
},
methods: {
editTodo: function (todo) {
this.editedTodo = todo
}
},
directives: {
focus: {
inserted (el) {
el.focus()
}
}
}
})
HTML
<div id="app">
Click the values to edit!
<ul class="todo-list">
<li v-for="todo in todos">
<input
v-if="todo.edit"
v-model="todo.title"
#blur="todo.edit = false; $emit('update')"
#keyup.enter="todo.edit=false; $emit('update')"
v-focus
>
<div v-else>
<label #click="todo.edit = true;"> {{todo.title}} </label>
</div>
</li>
</ul>
</div>
You can find more info here
https://v2.vuejs.org/v2/guide/custom-directive.html
With #AitorDB's help I have written a Vue component for this, I call it Click-to-Edit. It is ready to use, so I'm posting it.
What it does:
Supports v-model
Saves changes on clicking elsewhere and on pressing Enter
ClickToEdit.vue: (vue 2.x)
<template>
<div>
<input type="text"
v-if="edit"
:value="valueLocal"
#blur.native="valueLocal = $event.target.value; edit = false; $emit('input', valueLocal);"
#keyup.enter.native="valueLocal = $event.target.value; edit = false; $emit('input', valueLocal);"
v-focus=""
/>
<p v-else="" #click="edit = true;">
{{valueLocal}}
</p>
</div>
</template>
<script>
export default {
props: ['value'],
data () {
return {
edit: false,
valueLocal: this.value
}
},
watch: {
value: function() {
this.valueLocal = this.value;
}
},
directives: {
focus: {
inserted (el) {
el.focus()
}
}
}
}
</script>
Edit for 3.x: [Breaking changes between 2.x and 3.x]
remove .native from the event handlers
change the focus hook to mounted as described in Custom Directives 3.x.
Built on #Masen Furer's work. I added some protection to handle when a user deletes all of the data. There is probably a way to accomplish this using "update" but I couldn't get it working.
I also added the ability to hit escape and abandon any changes.
<template>
<span>
<input type="text"
v-if="edit"
:value="valueLocal"
#blur="save($event);"
#keyup.enter="save($event);"
#keyup.esc="esc($event);"
v-focus=""/>
<span v-else #click="edit = true;">
{{valueLocal}}
</span>
</span>
</template>
<script>
export default {
props: ['value'],
data () {
return {
edit: false,
valueLocal: this.value,
oldValue: (' ' + this.value).slice(1)
}
},
methods: {
save(event){
if(event.target.value){
this.valueLocal = event.target.value;
this.edit = false;
this.$emit('input', this.valueLocal);
}
},
esc(event){
this.valueLocal = this.oldValue;
event.target.value = this.oldValue;
this.edit = false;
this.$emit('input', this.valueLocal);
}
},
watch: {
value: function() {
this.valueLocal = this.value;
}
},
directives: {
focus: {
inserted (el) {
el.focus()
}
}
}
}
</script>

Vue `$refs` issues

I've an issue in this code
let bus = new Vue();
Vue.component('building-inner', {
props: ['floors', 'queue'],
template: `<div class="building-inner">
<div v-for="(floor, index) in floors" class="building-floor" :ref="'floor' + (floors - index)">
<h3>Floor #{{floors - index }}</h3>
<button type="button" class="up" v-if="index !== floors - floors">up</button>
<button type="button" class="down" v-if="index !== floors - 1">down</button>
</div>
</div>`,
beforeMount(){
bus.$emit('floors', this.$refs);
}
})
Vue.component('elevator', {
data: {
floorRefs: null
},
props: ['floors', 'queue'],
template: `<div class="elevator" ref="elevator">
<button type="button" v-for="(btn, index) in floors" class="elevator-btn" #click="go(index + 1)">{{index + 1}}</button>
</div>`,
beforeMount() {
bus.$on('floors', function(val){
this.floorRefs = val;
console.log(this.floorRefs)
})
},
methods: {
go(index) {
this.$refs.elevator.style.top = this.floorRefs['floor' + index][0].offsetTop + 'px'
}
}
})
new Vue({
el: '#building',
data: {
queue: [],
floors: 5,
current: 0
}
})
<div class="building" id="building">
<elevator v-bind:floors="floors" v-bind:queue="queue"></elevator>
<building-inner v-bind:floors="floors" v-bind:queue="queue"></building-inner>
</div>
I tried to access props inside $refs gets me undefined, why?
You should use a mounted hook to get access to the refs, because on "created" event is just instance created not dom.
https://v2.vuejs.org/v2/guide/instance.html
You should always first consider to use computed property and use style binding instead of using refs.
<template>
<div :style="calculatedStyle" > ... </div>
</template>
<script>
{
//...
computed: {
calculatedStyle (){
top: someCalculation(this.someProp),
left: someCalculation2(this.someProp2),
....
}
}
}
</script>
It's bad practice to pass ref to another component, especially if it's no parent-child relationship.
Refs doc
Computed

Categories