Vuejs component couldn't access data - javascript

I have a simple component but I couldn't access data inside component
This is my component
<template>
<!-- success -->
<div class="message-box message-box-success animated fadeIn" id="message-box-success">
<div class="mb-container">
<div class="mb-middle">
<div class="mb-title"><span class="fa fa-check"></span> {{title}} </div>
<div class="mb-content">
<p>{{successMessage}}</p>
</div>
<div class="mb-footer">
<button class="btn btn-default btn-lg pull-right mb-control-close" #click.prevent="close">OK</button>
</div>
</div>
</div>
</div>
<!-- end success -->
</template>
<script>
/* eslint-disable no-undef */
export default {
name: 'SuccessMsg',
props: {
title: ''
},
data () {
return {
successMessage: 'success'
}
},
methods: {
show: function (message) {
// in this line I'm getting undefined in console
console.log(this.successMessage)
// this.successMessage = message
$('#message-box-success').addClass('open')
},
close: function () {
$('#message-box-success').removeClass('open')
}
}
}
</script>
I have no problem in the other normal pages but in the component I couldn't access data.
Please help me to resolve this issue.
Thanks in advance

Thank you #IsraGab for your response and the code.
Your are right it's working but there is another problem that I didn't ask correctly.
It's not working when I'm calling the component method from main app in incorrect way.
After a day searching I find the solution.
Using Component Refs
The correct way to calling method is:
this.$refs.errMsg.show('some messages')
Where we have component tag like this:
<v-error ref="errMsg"></v-error>
Thanks again to all

Related

Vue-EventBus works only when it has the dedicated fuction for itself?

I came across a bug while transferring data using eventbus.
What I tried to do is
passing the data from 'Quoteinput.vue' to 'Quotebar.vue' to update the progress bar length
depending on the length of data which is in 'Quoteinput.vue'.
It was successfully done when I set two functions in 'Quoteinput.vue'.
One is for Pushing data to the array.
The other one is only for the eventbus.
See the code below.
=Quoteinput.vue=
<template>
<div>
<!-- <div class='input-group' style='position:relative'> -->
<div class='input-group-prepend'>
<span class = 'input-group-text'> Type your Quote</span>
</div>
<textarea class ='form-control' aria-label='with textarea' v-model="message"></textarea><hr><hr>
<button class="btn btn-primary" #click='addingmessage'>submit my quote</button>
<button class="btn btn-primary" #click='addprogress'>progresscheck</button>
<textbox class='messagebox' v-for='value in quote' :typedquote ='value'></textbox>
<!-- v model 이랑 v-for를 통해서 추가하면 되겠구만 -->
<!-- Text box showing -->
</div>
</template>
<script>
import textbox from './quotebox.vue'
import {ProgressBus} from '../../main.js'
export default {
data(){
return {
quote:[],
message:'',
}
},
components:{
textbox
},
methods:{
addingmessage(){
this.quote.push(this.message)
// 프로그레스 버스가 여기서 쿠오트 데이터를 물어가지고, 쿠오트바로 가져가야한다.
},
addprogress(){
ProgressBus.$emit('quotedata',this.quote)
}
}
}
However, this wasn't my original plan. I tried to put prgressbus and pushing the array within one function which is addingmessage(). like below.
methods:{
addingmessage(){
this.quote.push(this.message)
ProgressBus.$emit('quotedata',this.quote)
}
Why did this error happen? and what should I do to fix this?
The code that actually draws the progress bar is as below.
=Quotebar.vue=
<template>
<div class="progress" style="height: 20px;">
<div class="progress-bar" role="progressbar" :style="{width:10*completion+'%'}" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</template>
<script>
import {ProgressBus} from '../../main.js'
export default {
created(){
ProgressBus.$on('quotedata',(value)=>{
this.completion= value.length
})
},
data(){
return{
completion: 0
}
}
}
</script>
<style scoped>
</style>
For your understanding, I here attach simple diagram for the structure.
I'm curious what is the error message. I think you could async/await function for work sequentially.
methods:{
async addingmessage() {
await this.quote.push(this.message);
await ProgressBus.$emit('quotedata',this.quote);
}
}

Adding persistence to local storage to a Vue app

I am learning to deal with VueJS and made a simple todo app. It works well, but I want to store data locally and make it persistent even if there is a page reload.
This is the code produced following instruction of a few useful tutorials (leaving CSS outside to ease readability):
<template>
<div class="main-container">
<div class="header md-elevation-4">
<h1 class="md-title">{{ header }}</h1>
</div>
<div class="todo-list">
<div class="row"></div>
<div class="row">
<!-- add new todo with enter key -->
<md-field class="todo-input">
<md-input
v-model="currentTodo"
#keydown.enter="addTodo()"
placeholder="Add a todo! It's easy!"
/>
</md-field>
<!-- for all todos, set class of edited todos -->
<ul class="todos">
<div class="list-div">
<li v-for="todo in todos" :key="todo.id">
<!-- binds checkbox to todo model after each instance; -->
<input
class="toggle-todo"
type="checkbox"
v-model="todo.completed"
/>
<!-- starts editing process on double click -->
<span
class="todo-item-label"
:class="{ completed: todo.completed }"
#dblclick="editTodo(todo)"
v-if="!todo.edit"
>{{ todo.label }}</span
>
<!-- concludes editing with enter click -->
<input
v-else
class="todo-item-edit"
type="text"
v-model="todo.label"
#keyup.enter="completedEdit(todo)"
/>
<!-- deletes todos using removeTodo method -->
<i
class="material-icons"
alt="remove toDo"
#click="removeTodo(todo)"
>delete</i
>
</li>
</div>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
name: "RegularToolbar",
data() {
return {
header: "A VueJS ToDo App",
todos: [],
currentTodo: "",
completed: false, // add a completed property
editedToDo: null // add a edited property
};
},
methods: {
addTodo() {
this.todos.push({
id: this.todos.length,
label: this.currentTodo,
completed: false, // initializes property
edit: false // initializes property
});
this.currentTodo = "";
},
mounted() {
// console.log('App mounted!');
if (localStorage.getItem("todos"))
this.todos = JSON.parse(localStorage.getItem("todos"));
},
watch: {
todos: {
handler() {
// console.log('Todos changed!');
localStorage.setItem("todos", JSON.stringify(this.todos));
},
deep: true
}
},
removeTodo(todo) {
// allows users to remove todos
var index = this.todos.indexOf(todo);
this.todos.splice(index, 1);
},
editTodo(todo) {
todo.edit = true;
},
completedEdit(todo) {
todo.edit = false;
}
}
};
</script>
<style lang="scss" scoped></style>
As it is, all the JS part referring to mount and watch does not work. I am able to add new todos and delete them as I wish, but it does not retain the data if the user reloads the page.
Could some of the colleagues spot what I am missing here?
It's a problem of code organization:
Your mounted and watch sections are currently inside the methods section, which will prevent them from firing as expected.
Move those out into their own sections (both should be at the same level as methods) and you should be all set.
With those edits and nothing else, I've got your code working in a fiddle here: https://jsfiddle.net/ebbishop/dc82unyb/

push is not a function vuejs

I'm making an app with VueJS and Laravel. I'm getting an error, the push is not a function when I clicked an add to cart button. Everything is working here fine but methods addToCart gives error push is not a function. when I first click add to cart button it gives that error and once I refresh the page I can see a product in cart and again if click adds to cart button this time error is not seen, works perfectly. when cart[] is empty it gives error push is not a function, but when cart[] has at least one element I don't get that error.
Any help would be greatly appreciated.
productlist.vue
<template>
<div class="col-md-7">
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">{{ product.name }}</h5>
<p class="card-text">{{ product.price }}
</p>
<button class="btn btn-primary" #click="addProductToCart(product)">Add to cart</button>
</div>
</div>
</div>
</template>
<script type="text/javascript">
export default{
props:['product'],
data(){
return{
}
},
methods:{
addProductToCart(product){
axios.post('/products/create',{
product : product
}).then((response)=>{
console.log(response)
this.$emit('addedToCart',product)
});
}
}
}
</script>
cart.vue
<template>
<div class="col-md-4">
<li v-for="(item,index) in cart">
{{ item.name }}-{{ item.price }}
<button #click="removeitem(index)">Remove</button>
</li>
</div>
</template>
<script type="text/javascript">
export default{
props:['cart'],
}
</script>
Main.vue
<template>
<div>
<div class="col-md-7" v-for="product in products">
<Productlist :product="product" #addedToCart="addedToCart"></Productlist>
</div>
<Cart :cart="cart" ></Cart>
</div>
</template>
<script type="text/javascript">
import Productlist from './Productlist';
import Cart from './Cart';
export default{
data(){
return{
products:[],
cart: [ ]
}
},
mounted() {
//get all products and show in page
axios.get('/products')
.then((response)=>{
this.products = response.data;
});
// get only those products that are added to cart
axios.get('/list')
.then((response)=>{
this.cart= response.data;
console.log(response)
});
},
methods:{
addedToCart(product){
this.cart.push(product)
}
},
components:{Productlist,Cart}
}
</script>
i don't sure if this will resolve your problem but is unnecessary do:
<button class="btn btn-primary" #click="addProductToCart(product)">Add to cart</button>
because you have product as prop of the component, should be #click="addProductToCart" without problem.
and your method should be so:
addProductToCart() {
axios
.post('/products/create', {
product: this.product,
})
.then(response => {
console.log(response);
this.$emit('addedToCart', this.product);
});
}
One thing more, use kebab-case to call the key string when you emit to the parent component:
this.$emit('addedToCart', this.product);
replace it with:
this.$emit('added-to-cart', this.product);
Then in your parent component you have:
<Productlist :product="product" #addedToCart="addedToCart"></Productlist>
replace it with:
<Productlist :product="product" #added-to-cart="addedToCart"></Productlist>
I guess this last things will resolve your problem according the Vue documentation.

Updating unrelated Vue.js variable causing input values in template to disappear

I am having a weird issue with my single file Vue component where when I update an unrelated variable (Vue.js variable), all of my inputs (stuff I typed in, not the elements themselves.) disappear.
I have worked with Vue single file components for a few months now and I have never ran into something like this. Here is the weird part, the variable gets updated successfully as expected, but if I include the variable inside of the template at all that is when all the inputs disappear.
The function is looking up 'agents', then letting the user know how many records have been found and whether or not he/she would like to view them. If the user clicks on the "View" link, then they are shown a bootstrap-modal which shows them the records so that they could select one.
Here is what I have already tried:
Removing all ids from the inputs and using only refs="" to get the values.
changing the 'agents' variable name. Thought maybe it was conflicting with some rogue global or something.
Double checked that the parent component and this component was not being re-rendered. I did that by putting console.log() comments in the mounted() function and as expected it is only rendering once.
Watched the key using Vue dev tools extension to make sure the key was not being changed somehow.
Executed the searchAgent() function in a setTimeout(()=>{},5000) to see whether my use of _.debounce was causing issues.
Used jquery to fetch the values from the inputs instead of refs.
Assign the new records to a local variable agentsArray, then pass that into a function which assigns it to the vue variable 'agents' (its basically a needlessly longer route to the same thing but I thought WHY NOT TRY IT)
Double checked all my uses of 'this' to make sure that I was not accidentally using the wrong this and causing some unknown bug.
Using V-model, but using that doesn't help because I would still have to include the 'agents' inside of the modal in the template.
Using a v-if statement to render the modal HTML in the template only after 'agents' is not an empty array.
Update: Based on a suggestion, removed the function from inside of $(document).ready() inside of the mounted() function.
Template:
<template>
<div class="Q mb-0">
<i class="far fa-question-circle"></i>
<center>
<p class="display-1">{{title}}</p>
{{prefix}} is Representing Themselves Skip This Step.
<div id="searchResults" class="hidden" style="margin-top:5px;">
<a id="searchResultsText" class="SkipStepStyle"></a>
<a
id="viewSearchResults"
style="font-weight: bold;"
class="hidden SkipStepStyle"
v-on:click="displayAgents"
>
View
</a>
</div>
<form class="mt-2 BuyerSellerAgentInfo">
<div class="form-row">
<div class="form-group col-md-6">
<input
ref="NameFirst"
type="text"
:name="prefix+'sAgent_NameFirst'"
placeholder="FIRST NAME"
class="AnswerChoice"
:value="currentAnswers[prefix+'sAgent_NameFirst'].Answer"
>
</div>
<div class="form-group col-md-6">
<input
ref="NameLast"
type="text"
:name="prefix+'sAgent_NameLast'"
placeholder="LAST NAME"
class="AnswerChoice"
:value="currentAnswers[prefix+'sAgent_NameLast'].Answer"
>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<input
ref="Email"
type="text"
:name="prefix+'sAgent_Email'"
placeholder="EMAIL ADDRESS"
class="AnswerChoice"
:value="currentAnswers[prefix+'sAgent_Email'].Answer"
>
</div>
<div class="form-group col-md-6">
<input
ref="Phone"
type="text"
:name="prefix+'sAgent_Phone'"
maxlength="14"
placeholder="PHONE #"
class="AnswerChoice"
:value="currentAnswers[prefix+'sAgent_Phone'].Answer"
>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<input
ref="Brokerage"
type="text"
:name="prefix+'sAgent_Brokerage'"
placeholder="AGENT'S BROKERAGE"
class="AnswerChoice"
:value="currentAnswers[prefix+'sAgent_Brokerage'].Answer"
>
</div>
<div class="form-group col-md-6">
<input
ref="License"
type="text"
:name="prefix+'sAgent_License'"
placeholder="AGENT'S LICENSE #"
class="AnswerChoice"
:value="currentAnswers[prefix+'sAgent_License'].Answer"
>
</div>
</div>
<input
class="AnswerChoice"
type="hidden"
:name="prefix+'sAgent_ID'"
:value="currentAnswers[prefix+'sAgent_ID'].Answer || '1'"
>
<input
class="AnswerChoice"
type="hidden"
:name="prefix+'sAgent_BrokerageID'"
:value="currentAnswers[prefix+'sAgent_BrokerageID'].Answer || '1'"
>
</form>
</center>
<div v-if="agents.length > 0" class="modal" id="AgentPopup">
<div class="vertical-alignment-helper">
<div class="modal-dialog vertical-align-center">
<div class="modal-content">
<div class="modal-body">
<center>
<h5 class="d-inline-block mb-3">Select {{prefix}}'s Agent:</h5>
</center>
<button v-on:click="displayCategories" type="button" class="close shadow" data-dismiss="modal">×</button>
<ul>
<li v-for="agent in agents">{{ agent.NameFull || agent.NameFirst+' '+agent.NameLast }}</li>
<li class="border-0">{{prefix}}’s agent is not in this list</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
Script:
import _ from 'lodash';
export default {
name: "AgentInformation",
props: {
friendlyIndex: {
type: String,
default: null,
},
title: {
type: String,
default: null,
},
answerChoices:{
type: Array,
default: () => []
},
currentAnswers: {
type: Object,
default: () => {},
},
prefix: {
type: String,
default: '',
},
token: {
type: String,
default: '',
},
},
methods: {
debounceFunction(func,timer){
let vueObject = this;
return _.debounce(()=>{
vueObject[func]();
},timer);
},
displayCategories(){
$('.categories').show();
},
displayAgents(){
$('.categories').hide();
$('#AgentPopup').modal({backdrop:'static',keyboard:false});
},
searchAgent() {
let vueObject = this;
console.log('calling searchAgent()');
let agentSearchRoute = correctVuexRouteURL(vueObject.$store.getters.routeName('search.agent'));
if (!agentSearchRoute) genericError('Agent Search Route Not Found. Error code: a-s-001');
else
{
let dataObject = {
NameFirst: this.$refs.NameFirst.value,
NameLast: this.$refs.NameLast.value,
Email: this.$refs.Email.value,
Phone: this.$refs.Phone.value,
License: this.$refs.License.value,
_token: this.token,
};
console.log(dataObject);
vueObject.$http.post(agentSearchRoute, dataObject).then((r) => {
let status = r.body.status;
if (status == 'success')
{
vueObject.agents = r.body.agents;
let searchResultsContainer = $('#searchResults');
let searchResultsText = $('#searchResultsText');
let viewSearchResultsLink = $('#viewSearchResults');
let agentCount =
vueObject.agents.length;
searchResultsContainer.removeClass('hidden');
if(agentCount > 0)
{
let rText = agentCount > 1 ? 'records' :
'record';
searchResultsText.text(agentCount+' '+rText+'
found.');
viewSearchResultsLink.removeClass('hidden');
}
else
{
if (!viewSearchResultsLink.hasClass('hidden'))
viewSearchResultsLink.addClass('hidden');
searchResultsText.text('No records found.');
}
}
});
}
},
},
data(){
return {
agents: [],
}
},
mounted() {
let vueObject = this;
console.log('mounted');
$(document).ready(function(){
$('#phone').mask('(###)-###-####');
$('.AnswerChoice').on('input', () => {
let searchAgent =
vueObject.debounceFunction('searchAgent',500);
searchAgent();
});
});
}
}
It seems that the issue is the template does not like the 'agents' variable to be inside of it. When I remove the modal container or just the references to 'agents' it works as expected. If I change the variable name it does not solve the issue.
Any thoughts on the solution? Am I missing something blatantly obvious and stupid?!
Edit: Something I forgot to add, I don't think affects this in any way but it is worth mentioning. This component is rendered dynamically inside of the parent.
Rendering the component:
<component
v-for="(component,i) in selectedView"
:is="component['Component']"
v-bind="bindAttributes(component)"
:key="component.ID"
>
</component>
Changing agents will cause the whole template to be re-run. Not just the bits that mention agents, everything in that template will be updated.
When a user types into one of your <input> elements you aren't storing that value anywhere. You've got a :value to poke the value in but you aren't updating it when the value changes. The result will be that when Vue re-renders everything it will jump back to its original value.
You should be able to confirm this by setting the initial values within currentAnswers to be something other than empty. You should find that whenever agents changes it jumps back to those initial values.
The solution is just to ensure that your data is kept in sync with what the user types in. Typically this would be done using v-model but that's a bit tricky in this case because you're using a prop for the values and you shouldn't really be mutating a prop (one-way data flow). Instead you should use events to communicate the required changes up to whichever component owns that data.
Here is a simple test case to demonstrate the issue in isolation:
new Vue({
el: '#app',
data () {
return {
count: 0,
value: 'initial'
}
}
})
<script src="https://unpkg.com/vue#2.6.10/dist/vue.js"></script>
<div id="app">
<input :value="value">
<button #click="count++">Click count: {{ count }}</button>
</div>

VueJs Send data to modal component

i want to send my data (first component) to modal (another component). Both component are located in this same place. I need show data to first component data form to my edit modal.
Here is my code:
form.vue :
<template>
<tbody v-for="user,index in users">
<button type="button" class="btn btn-xs" data-toggle="modal"
data-target="#editModal"> -> edit button, show modal
(...)
<edit-user></edit-user>
(...)
</template>
<script>
components: {
add: addUser,
edit: editUser
},
</script>
edit.vue:
<template>
<div id="editModal" class="modal fade" role="dialog">
<div class="form-group">
<input type="text" class="form-control" name="nameInput"
value=" I WANT HERE DATA" v-model="list.name">
</div>
(...)
</template>
How can i do this?
A solution would be having the parent component to store the data that both components share.
On the first component you can use $emit to change that data of the parent and then pass that same data to the modal component using props.
Vue.component('app-input', {
props: ['message'],
template: `<input type="text" placeholder="Try me"
v-bind:value="message"
v-on:input="$emit('input', $event.target.value)"/>`
});
Vue.component('app-header', {
props: ['title'],
template: `<h4>{{title}}</h4>`
});
var app = new Vue({
el: '#app',
data: {
message: ''
}
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<app-header v-bind:title="message"></app-header>
<app-input v-model="message"></app-input>
</div>
The above is a simple example of how it can be done.
The <app-input> component changes the parent message data, and that same property is passed to the <app-header> component as the title.

Categories