How to pass computed function into v-bind and v-on? - javascript

I know it's simple example, but I'm new to Vue.
I'm sure that error is where I pointed. I'm trying to call function from computed method. There is no problem if write code straight to v:bind, but once I pass it throug func it gives me error. As well I know that from method functions call as func(), but I guess from computed they have another syntax.
<body>
<div class="container">
<hr>
<div class="sample">
<input type="text" v-bind:value="name" v-on:input="name = $event.target.value">
<hr>
<h2>Hello, {{ name }}</h2>
<input type="button" value="Click on it" v-on:click="addNumber()">
<hr>
<div v-for="num in numbers">
{{ num }}
</div>
<input type="button" v-on:click="show" v-bind:title="btnText" > //I'M SURE ERROR IS HERE
<h2 v-show="showH2">check hide</h2>
</div>
<div></div>
<script>
let sample = new Vue({
el: '.sample',
data:
{
showH2: true,
name: '12344',
numbers: []
},
methods:
{
addNumber()
{
let num = Math.floor(Math.random() * 11) - 5;
this.numbers.push(num);
}
},
computed:
{
btnText()
{
return this.showH2 ? 'Hide' : 'Show';
},
sum()
{
let sum = 0;
this.numbers.forEach((el) => sum += el);
return sum;
},
show()
{
this.showH2 = !this.showH2;
}
}
});
</script>
</body>
</html>

You are perfectly correct when you say- "There is no problem if write code straight to v:bind, but once I pass it through func it gives me error". This is because You don't call a computed and it doesn't accept any parameters. You reference a computed property just like you would a data property. Whereas a method is just a function bound to the Vue instance. It will only be evaluated when you explicitly call it. So if you shift show in methods it will work. vue doc

Related

JQuery: Loop through elements and set as variable for outside scope

I am trying to retrieve a DOM element from an array, and I want to set it as a variable to use outside its scope. Right now, my variable future_devices returns one object as expected. But my other variable future_device returns the object when the current DOM should have returned [] due to my last if statement. I originally tried to declare my variables as var due to scope but that did not help. Here is my code:
var future_devices = $('.hardware .future-hardware')
if (future_devices.length) {
let future_device = $(future_devices)
.each(function() {
let device = this
let device_work_order = $(device)
.data(
'work-order'
)
if (device_work_order == data['new_host']['work_order']) {
return device
}
})
I can tell you on the said DOM, the two variables I am using to compare have the following values:
device_work_order = 3MOD0
data['new_host']['work_order'] = 3MOD9
So since future_devices returns only one object and my last if statement is not true, I should get [], right?
$(...) is returning the jQuery collection and always will regardless. So an assignment statement using .each() is the wrong approach.
Solution: Assign the return of .filter() instead. Filter is designed to accomplish your goal. Reference
NOTE: You should realize that if there is more than one match, it will return the entire collection of matches. In the code below I show only the first match, but since there are two matches (for demonstration), you'll see that both matches are returned.
const future_devices = $('.hardware .future-hardware');
const data = {new_host: {work_order: 333}};
const future_device = $(future_devices)
.filter(function(idx, el) {
let device_work_order = $(el).data('work-order');
if (device_work_order == data['new_host']['work_order']) {
return true;
} else {
return false;
}
})
console.log("First match only: ", future_device[0]); // First match
console.log("Collection: ",future_device); // All matches
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hardware">
<div class="future-hardware" data-work-order="111">111</div>
</div>
<div class="hardware">
<div class="future-hardware" data-work-order="333">First Match</div>
</div>
<div class="hardware">
<div class="future-hardware" data-work-order="111">111</div>
</div>
<div class="hardware">
<div class="future-hardware" data-work-order="333">Second Match</div>
</div>
<div class="hardware">
<div class="future-hardware" data-work-order="111">111</div>
</div>
<div class="hardware">
<div class="future-hardware" data-work-order="111">111</div>
</div>

Vue.js - How to use an array in function for looping

I want to use a JS array in Vue.js function for looping.
Tried code:
Vue:
computed: {
bbb: function(){
var vvv=this.Preused.length-this.quote.lines.length;
let added_products=[];
if(vvv > 0){
for(var i = 0; i <= vvv-1; i++){
newly_used.push({...this.Preused[this.manage.code.length+i]});
}
}
return newly_used;
}
}
HTML:
<div v-for="(cc,index) in bbb">
<p v-text="cc[index].num"></p>
</div>
newly_used:
0:
none: "calibry"
des: "Silver"
num: "numty"
By using the above code I am getting the following error;
[Vue warn]: Error in render: "TypeError: Cannot read property 'num' of undefined"
How Can I solve this?
cc.num may work, cc is single item in bbb, and you shoule check if cc exist
You're looping through newly_used properties which is returned from computed property so your v-for should be like :
<div v-for="(cc,index) in bbb" :key="index">
<p v-text="cc.num"></p>
</div>
or
<div v-for="(cc,key,index) in bbb" :key="index">
<p v-text="bbb[key].num"></p>
</div>

How to get return of one function with parameter in other function in Javascript

I am new to JavaScript and kind of stuck at this place
function onView(data){
var item_size = data;
return item_size;
}
I have this function with parameter passing through HTML input, i want to use return of this function in another function
function onRegisterInput(){
var y= onView(data);
}
onRegisterInput is called onclick Button, i want to take return value of onView function as var y.
How can i do this ??
Everytime i click button onRegisterInput() function is called but my debugger shows data is undefined. Please help. Thanks in advance.
As you can see in onView, it takes data as function parameter, however you don't give it any parameter in your call var y= onView();. From my understanding, onView get's triggered when a button is clicked, so I'd suggest you save your value in a global variable so you can use it across functions
There are 2 ways for you to get the data in your button click callback.
Get data from the DOM
There are different ways to keep data inside the DOM, but data-* attributes are popular:
function testMe(event, button) {
const magicNumber = button.getAttribute('data-magic-number');
document.getElementById('result1').innerHTML = magicNumber;
}
function testMe2(event, button) {
const magicNumber = document.getElementById('magic2').getAttribute('data-magic-number');
document.getElementById('result2').innerHTML = magicNumber;
}
.test {
padding: 4px;
}
<div class="test">
<button id="button1" data-magic-number="123456789" onclick="testMe(event, this)">Button 123456789</button>
<div id="result1"></div>
</div>
<div class="test">
<span data-magic-number="987654321" id="magic2">Click this: </span><button id="button2" onclick="testMe2()">Button 987654321</button>
<div id="result2"></div>
</div>
Another option is to keep data inside the JS
let myMagicNumber = 1;
let resultDiv = document.getElementById('result');
function showNumber() {
resultDiv.innerText = myMagicNumber;
}
function incNumber() {
myMagicNumber++;
showNumber();
}
function decNumber() {
myMagicNumber--;
showNumber();
}
<div>
<button onclick="showNumber()">Show</button>
<button onclick="incNumber()">+1</button>
<button onclick="decNumber()">-1</button>
</div>
<div id="result">
</div>
Let's return to your example
function onView(data) {
// Some data processing
// We will return data length for example
return (typeof data === 'string' ? data.length : 0);
}
function onRegisterInput() {
// Button click
let data = document.getElementById('name').value;
if (data != '') {
var y = onView(data);
document.getElementById('result').innerText = 'Name: ' + data + ', length: ' + y;
} else {
document.getElementById('result').innerText = 'Enter your name';
}
}
<div>
<label>Name: <input type="text" id="name"/></label>
<button onclick="onRegisterInput()">Register</button>
</div>
<div id="result"></div>

Calling A function using vue.js components and properties

I am creating a shopping cart type button to count the number of times clicked, the button should call a function when clicked with the parameter of the id, however, it won't call the function with the correct parameter
I have tried adding {{id}} and :onClick="addThisToCart({{id}} but getting a ton of errors.
Heres my code
Vue.component('movietable', {
props: ['title', 'price', 'mid'],
template: `
<tr>
<td>{{title}}</td>
<td>{{price}}</td>
<td>
<div class="quantity">
<button onClick="addThisToCart({{mid}}">You clicked me {{ count }} times.</button>
</div>
</td>
</tr>
`,
data: function () {
return {
count: 0
}
},
});
mid is being defined in the properties section of the vue element
and then the function
var cart = 0;
function addThisToCart(movieId) {
var movieId = this.mid;
this.cart += 1;
this.cart += 1;
console.log(movieId);
console.log(cart);
}
It should add +1 to cart every time the button is clicked, however, getting a ton of errors and instead of sending '4434' it is sending {{mid}}
You can use
<button #click="addThisToCart(mid)">You clicked me {{ count }} times.</button>
No curly braces for the argument of the function.

Getting random values from objects inside an array by clicking a button

I need to a get a random string from the objects inside an array when you click the button. But for some reason my code is not executing.
var quotes = [{
quote: "Quote1",
source: "Source1"
},
{
quote: "Quote2",
source: "Source2"
},
{
quote: "Quote3",
source: "Source3"
},
{
quote: "Quote4",
source: "Source4"
},
{
quote: "Quote5",
source: "Source5"
}
];
function getRandomquote() {
var randomindex = Math.floor(Math.random() * (quotes.length));
var quotesarr = quotes[randomindex];
var objquote = quotesarr.quote;
var objsource = quotesarr.source;
document.getElementById("quote").innerHTML = objquote;
document.getElementById("source").innerHTML = objsource;
}
function printQuote() {
document.getElementById("loadQuote").onclick = getRandomquote;
}
printQuote();
<div class="container">
<div id="quote-box">
<p class="quote"> hello</p>
<p class="source"> hello</p>
</div>
<button id="loadQuote" onclick="printQuote();">Show another quote</button>
I am getting this error message:
Uncaught TypeError: Cannot set property 'innerHTML' of null
at HTMLButtonElement.getRandomquote (randomtest1.js:27)
Update after answers below
I changed getElementById to getElementsByClassName, and now there are no error messages.
But when I click the button, it does not change the elements. I believe I have made a mistake on the printQuote function. I cannot figure it out.
You'll need to add the ids to the elements as below. Or use getElementsByClassName() or use querySelector(".quote").
var objquote = "Hello";
var objsource = "World";
document.getElementById("quote").innerHTML=objquote;
document.getElementById("source").innerHTML=objsource;
<div id="quote-box">
<p id="quote" class="quote"> hello</p>
<p id="source" class="source"> hello</p>
</div>
You can't use getElementById to retrieve an element by its class. You'll need to specify an id or use getElementsByClassName- https://developer.mozilla.org/en/docs/Web/API/Document/getElementsByClassName
var els = document.getElementsByClassName('test')
console.log(els.length)
<div class="test"></div>
In your example:
<p class="quote" id="quote"> hello</p>
<p class="source" id="source"> hello</p>
Please find the working code below. i have removed unwanted functions.
html
<div id="quote-box">
<p class="quote">hello</p>
<p class="source">hello</p>
</div>
<button id="loadQuote" onclick="getRandomquote();">Show another quote</button>
js
var quotes=[
{quote:"Quote1", source:"Source1"},
{quote:"Quote2", source:"Source2"},
{quote:"Quote3", source:"Source3"},
{quote:"Quote4", source:"Source4"},
{quote:"Quote5", source:"Source5"}
];
getRandomquote=function(){
var randomindex=Math.floor(Math.random()*(quotes.length));
var quotesarr=quotes[randomindex];
document.getElementsByClassName("quote")[0].innerHTML=quotesarr.quote;
document.getElementsByClassName("source")[0].innerHTML=quotesarr.source;
}
you have not set id in your p tag ...please set id='quote' and it should start working.
I changed getElementById to getElementsByClassName, and now there are no error messages.
But when I click the button, it does not change the elements. I believe I have made a mistake on the printQuote function. I cannot figure it out.

Categories