<script>
var app = new Vue ({
el: '#app',
data : {
sentence: ''
},
methods: {
Q: function () {
this.sentence = "Q"
},
W: function () {
this.sentence = "W"
},
E: function () {
this.sentence = "E"
},
R: function () {
this.sentence = "R"
},
T: function () {
this.sentence = "T"
},
Y: function () {
this.sentence = "Y"
}
}
})
</script>
<div id="app">
<p>Sentence : {{ sentence }}</p>
<button #click="Q">Q</button>
<button #click="W">W</button>
<button #click="E">E</button>
<button #click="R">R</button>
<button #click="T">T</button>
<button #click="Y">Y</button>
</div>
The program is working. But first of all the user click 'Q' and after that click 'W', the input seems 'W' , i want this input: "QW" , it should be combine.
For example the user click Q, W and E, the input should be "QWE". How can i combine all of them? Maybe its easy but i couldnt find anywhere. I am beginner on VueJS
Can you help me?
You can easily concat the string from your template #click event like so :
Method 1
<div id="app">
<p>Sentence : {{ sentence }}</p>
<button #click="sentence += 'Q'">Q</button>
<button #click="sentence += 'W'">W</button>
<button #click="sentence += 'E'">E</button>
<button #click="sentence += 'R'">R</button>
<button #click="sentence += 'T'">T</button>
<button #click="sentence += 'Y'">Y</button>
</div>
Method 2
<div id="app">
<p>Sentence : {{ sentence }}</p>
<button #click="addToSentence('Q')">Q</button>
<button #click="addToSentence('W')">W</button>
<button #click="addToSentence('E')">E</button>
<button #click="addToSentence('R')">R</button>
<button #click="addToSentence('T')">T</button>
<button #click="addToSentence('Y')">Y</button>
</div>
with a dedicated method
data() {
return {
sentence: ''
}
},
methods: {
addToSentence(letter) {
this.sentence += letter
}
}
Method 3
<div id="app">
<p>Sentence : {{ sentence }}</p>
<button v-for="letter in ['Q','W','E','R','T','Y']" #click="addToSentence(letter)">{{ letter }}</button>
</div>
with a dedicated method
data() {
return {
sentence: ''
}
},
methods: {
addToSentence(letter) {
this.sentence += letter
}
}
Method 4
More compact
<div id="app">
<p>Sentence : {{ sentence }}</p>
<button v-for="letter in ['Q','W','E','R','T','Y']" #click="sentence += letter">{{ letter }}</button>
</div>
data() {
return {
sentence: ''
}
},
What you looking for is called concatenation
add an + infront of =
Example:
this.sentence = "Q" to this.sentence += "Q"
Thats the same as if you would write: this.sentence = this.sentence + "Q" its just a shortcut
var app = new Vue ({
el: '#app',
data : {
sentence: ''
},
methods: {
Q: function () {
this.sentence += "Q"
},
W: function () {
this.sentence += "W"
},
E: function () {
this.sentence += "E"
},
R: function () {
this.sentence += "R"
},
T: function () {
this.sentence += "T"
},
Y: function () {
this.sentence += "Y"
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<p>Sentence : {{ sentence }}</p>
<button #click="Q">Q</button>
<button #click="W">W</button>
<button #click="E">E</button>
<button #click="R">R</button>
<button #click="T">T</button>
<button #click="Y">Y</button>
</div>
Related
Beginner to Vue and JavaScript - but learning ))
I have a Vue Mains App, and a sub-component handling a form (Calculate the difference between 2 values).
I wish the values of the form to be reset to the initial value when the mains App "Reset" button is clicked.
I have 2 problems:
the page reloads when I click on the form button "Calculate Difference"
the "Reset" is not resetting the initial value - it seems the event is not distributed to the sub-component.
On loading the page I have the following warning that I can't interpret:
[Vue warn]: Property "reset" was accessed during render but is not defined on the instance. at
Here is the all in one-page sample code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Difference</title>
<script src="https://unpkg.com/vue#next"></script>
</head>
<body>
<div id="app">
<br> Change Values, Click "Calculate Difference", then "Reset" to set Back to 0
<br>
<calculator v-on:reset="reset" :start_val="0" :end_val="0"> </calculator>
<br>
<button class="button" v-on:click="onResetButton()"> Reset </button>
</div>
</body>
<script>
const vm = Vue.createApp({
emits: {
'reset': null
},
methods: {
onResetButton() {
console.log("onResetButton $emit")
this.$emit('reset');
},
},
})
vm.component('calculator', {
props: ['start_val', 'end_val'],
data() {
return {
calculator: {
start_val: this.start_val,
end_val: this.end_val,
difference: this.end_val - this.start_val,
},
}
},
methods: {
onDifference() {
console.log("onDifference")
this.calculator.difference = this.calculator.end_val - this.calculator.start_val
console.log(this.calculator.difference)
},
reset() {
calculator.start_val = this.start_val
calculator.end_val = this.end_val
calculator.difference = this.end_val - this.start_val
console.log("reset calculator")
}
},
template: `
<hr>
<form>
<br> Start Value : <input class="input" type="number" v-model.number="calculator.start_val">
<br> End Value : <input class="input" type="number" v-model.number="calculator.end_val">
<br> <button class="button" v-on:click="onDifference()">Calculate Difference </button>
</form>
<p>Difference : {{ calculator.difference }} </p>
<hr>
`
})
vm.mount('#app');
</script>
</html>
Here's a small snippet that probably gives you ideas:
const {
reactive,
ref,
toRefs,
computed
} = Vue
const Calculator = {
props: {
startVal: {
type: Number,
default: 0,
},
endVal: {
type: Number,
default: 0,
},
},
emits: ['update:startVal', 'update:endVal'],
setup(props, {
emit
}) {
const start_val = computed({
get() {
return props.startVal
},
set(val) {
emit('update:startVal', val || 0)
},
})
const end_val = computed({
get() {
return props.endVal
},
set(val) {
emit('update:endVal', val || 0)
},
})
return {
start_val,
end_val
}
},
template: `
<div>
{{ start_val }} / {{ end_val }}<br />
StartVal: <input v-model.number="start_val" /><br />
EndVal: <input v-model.number="end_val" />
</div>
`
}
const initState = () => ({
startVal: 0,
endVal: 0
})
const App = {
setup() {
const state = reactive(initState())
const result = computed(() => {
return state.startVal + state.endVal
})
const resetState = () => {
const defaultState = initState()
for (let key in state) {
state[key] = defaultState[key]
}
}
return {
result,
...toRefs(state),
resetState,
}
},
template: `
<div>
Result: {{ result }}<br />
<button
#click="resetState"
>
RESET
</button>
<Calculator
v-model:startVal="startVal"
v-model:endVal="endVal"
/>
</div>
`
}
const vm = Vue
.createApp(App)
vm.component('Calculator', Calculator)
vm.mount('#app')
<script src="https://unpkg.com/vue#next"></script>
<div id="app"></div>
Creating a filter to sort through quotes data, but having problems with creating the correct functions.
HTML:
<template>
<div class="home">
<h1>{{ message }}</h1>
<h3> Theme filter: </h3>
<div>
<button v-on:click="userFilterKey = 'movies'"> Search movies</button>
<button v-on:click="userFilterKey= 'all'"> Search all</button>
<button v-on:click="userFilterKey= 'games'"> Search games </button>
<div v-for="quote in quotes" v-bind:key="quote.id">
<p>Souce: {{ quote.source }} </p>
<p>Quote: {{ quote.quote }} </p>
<p>Theme: {{ quote.theme }} </p>
</div>
</div>
</div>
</template>
Script:
import axios from "axios";
export default {
data: function () {
return {
message: "Welcome to Vue.js!",
quotes: [],
userFilterKey: "all",
};
},
methods: {
userFilter: function () {
return this[this.userFilterKey];
},
all: function () {
return this.quotes;
},
movies: function () {
return this.quotes.filter((theme) => (quotes.theme = "movies"));
},
books: function () {
return this.quotes.filter((theme) => (quotes.theme = "books"));
},
quotesIndex: function () {
axios
.get("linktodata")
.then((response) => {
this.quotes = response.data;
});
},
How do I create filters to sort through the theme key of the quotes array within my link?
Use a computed prop.
new Vue({
el: '#app',
data: () => ({
quotes: [{
id: 1,
source: 'a',
quote: '',
theme: ''
},
{
id: 2,
source: 'b',
quote: '',
theme: 'movies'
},
{
id: 3,
source: 'c',
quote: '',
theme: 'games'
}
],
userFilterKey: "all"
}),
computed: {
filteredQuotes() {
if (this.userFilterKey === 'all') {
return this.quotes
}
return this.quotes.filter(v => v.theme === this.userFilterKey)
}
}
})
<div id="app">
<button #click="userFilterKey = 'all'"> Search all </button>
<button #click="userFilterKey = 'movies'"> Search movies</button>
<button #click="userFilterKey = 'games'"> Search games </button>
<div v-for="quote in filteredQuotes" :key="quote.id">
<p>Souce: {{ quote.source }} </p>
<p>Quote: {{ quote.quote }} </p>
<p>Theme: {{ quote.theme }} </p>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.14/vue.min.js"></script>
Try using Pipes. Its something that does the filter in client side and is faster. may be that solves your problem
I am trying to change the background colour of an element on click of it using vue but it doesn't change, this is what i have come up with so far, also the onclick method has two functions and I read that this is the best way to input to onclick events in vue.
<div id="exercise">
<div>
<p>Current Value: {{ value }}</p>
<button #click="value += 5(); red();" :style="{ 'background-color': color }">Add 5</button>
<button #click="value += 1">Add 1</button>
<p>{{ result }}</p>
</div>
<div>
<input type="text" v-model="timer">
<p>{{ value }}</p>
</div>
</div>
js
new Vue({
el: "#exercise",
data: {
value: 0,
timer: 1000,
},
methods:{
red() {
this.color = "red";
}
},
computed: {
result: function() {
return this.value >= 37 ? "Not there yet" : "done";
}
},
watch: {
result: function(value) {
var vm = this;
console.log(value);
setTimeout(function() {
vm.value = 0;
}, 5000);
}
}
});
In data you must insert
data: {
value: 0,
timer: 1000,
color: null
},
and try use correct syntax: https://v2.vuejs.org/v2/guide/class-and-style.html#Object-Syntax-1
<button #click="value += 5(); red();" :style="{backgroundColor: color }">Add 5</button>
I need a background colour to go back to its default colour after 3 seconds, I am using the setTimeout method but it is not working, how do I properly use it in this situation? or do I use a transition
<div id="exercise">
<div>
<p>Current Value: {{ value }}</p>
<button #click="value += 5(); red();" :style="{ 'background-color': color }">Add 5</button>
<button #click="value += 1">Add 1</button>
<p>{{ result }}</p>
</div>
<div>
<input type="text" v-model="timer">
<p>{{ value }}</p>
</div>
</div>
new Vue({
el: "#exercise",
data: {
value: 0,
timer: 1000,
color:'pink',
},
methods:{
red() {
this.color = "red";
setTimeout(function() {
this.red = 0;
}, 1000);
}
},
computed: {
result: function() {
return this.value >= 37 ? "Not there yet" : "done";
}
},
watch: {
result: function(value) {
var vm = this;
console.log(value);
setTimeout(function() {
vm.value = 0;
}, 5000);
}
}
});
Try to use an arrow function for your setTimeout, as the setTimeout points the this to the global object. Arrow functions use lexical scoping and knows to bind the this to the inner function:
new Vue({
el: "#exercise",
data: {
value: 0,
timer: 1000,
color:'pink',
},
methods:{
red() {
this.color = "red";
setTimeout(() => {
this.color = "";
}, 1000);
}
},
computed: {
result: function() {
return this.value >= 37 ? "Not there yet" : "done";
}
},
watch: {
result: function(value) {
var vm = this;
console.log(value);
setTimeout(function() {
vm.value = 0;
}, 5000);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="exercise">
<div>
<p>Current Value: {{ value }}</p>
<button #click="red();" :style="{ 'background-color': color }">Add 5</button>
<button #click="value += 1">Add 1</button>
<p>{{ this.result }}</p>
</div>
<div>
<input type="text" v-model="timer">
<p>{{ value }}</p>
</div>
</div>
(Also, inside of your setTimeout, you were trying to change this.red = 0, when it should be this.color = "" :D
I have 3 desks in a table having role_id 2, 4 and 6. I have two tables. I want to display a different role name on a button based on the current user's role_id.
I want to display:
the role name having role_id 4 if the current user_role_id = 2
the role name having role_id 6 if the current user_role_id = 4.
user table
registration table
code
<span v-if="user.user_role_id ==results.desk_user_role_id">
<v-btn small color="primary" v-on:click="getNextDesk" style="width:400px;">Forward to </v-btn>
<v-btn small color="primary" v-on:click="getPreviousDesk" style="width:400px;">Revert </v-btn>
</span>
Script code
getNextDesk(currentdeskid) {
if (currentdeskid === 2) {
return 'Technical Desk';
}
if (currentdeskid === 4) {
return 'Executive Desk';
}
return '';
},
getPreviousDesk(currentdeskid) {
if (currentdeskid === 6) {
return 'Technical Desk';
}
if (currentdeskid === 4) {
return 'Registration Desk';
}
return '';
},
This is my best guess about what you're trying to do:
new Vue({
el: "#app",
data() {
return {
user: { user_role_id: 2 },
roles: {
2: { name: 'Registration', next: 4 },
4: { name: 'Technical', next: 6, previous: 2 },
6: { name: 'Executive', previous: 4 }
}
}
},
computed: {
forwardTo() {
const { next } = this.roles[this.user.user_role_id];
return next ? 'Forward to ' + this.roles[next].name : false;
},
revertTo() {
const { previous } = this.roles[this.user.user_role_id];
return previous ? 'Revert to ' + this.roles[previous].name : false;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
User:
<select v-model="user.user_role_id">
<option v-for="(role, id) in roles" :value="id">{{ role.name }}</option>
</select>
</div><br />
<button v-show="forwardTo">{{ forwardTo }}</button>
<button v-show="revertTo">{{ revertTo }}</button>
</div>