Vue, separate component fires off 'not a function' message - javascript

Everything here displays and acts how i want except for my call to the setInputName function. I believe the reason for this is because that happens within the tabs component which is built on a separate component and template, which then uses another component/template tab for the individual list item tabs.
The problem here is that when I click my list items, the console prints that _vm.setInputName is not a function
How can I fix this to be able to call this function from within the rendered template?
<tabs>
<tab name="Activity" :selected="true">
<div class="row notesInput" id="notesInput">
<div class="col-lg-12">
<div class="tabs">
<ul style="border-bottom:none !important; text-decoration:none">
<li v-on:click="setInputName('public')">Public</li>
<li v-on:click="setInputName('public')">Internal</li>
</ul>
</div>
<div>
<input type="text" v-bind:name="inputName">
<br>
Input name is: {{ inputName }}
</div>
</div>
</div>
</tab>
</tabs>
<script>
Vue.component('tabs', {
template: `
<div>
<div class="tabs">
<ul>
<li v-for="tab in tabs" :class="{ 'is-active': tab.isActive }">
<a :href="tab.href" #click="selectTab(tab)">{{ tab.name }}</a>
</li>
</ul>
</div>
<div class="tabs-details">
<slot></slot>
</div>
</div>
`,
data() {
return {
tabs: [],
};
},
created() {
this.tabs = this.$children;
},
methods: {
selectTab(selectedTab) {
this.tabs.forEach(tab => {
tab.isActive = tab.name == selectedTab.name;
});
} } });
Vue.component('tab', {
template: `
<div v-show="isActive"><slot></slot></div>
`,
props: {
name: { required: true },
selected: { default: false } },
data() {
return {
isActive: false,
};
},
computed: {
href() {
return '#' + this.name.toLowerCase().replace(/ /g, '-');
} },
mounted() {
this.isActive = this.selected;
} });
export default {
components: {
Multipane,
MultipaneResizer,
},
data () {
return {
inputName: '',
}
},
computed: {
},
methods: {
setInputName(str) {
this.inputName = str;
}
};
</script>

I think the issue is because you are calling the function from another component.
but your function is in another function. If you want this to work then you should extend your component in which your function exists and then you can use it.

Related

How to pass props to child component in vue

I have a parent component where I am doing the API call and getting the response. So what I am trying to do is pass this response as a prop to child component in Vue.
So here is my parent component and the call:
<button class="btn button col-2" #click="addToCart()">
Add to cart
</button>
addToCart: function () {
let amount = this.itemsCount !== "" ? this.itemsCount : 1;
if(this.variationId != null) {
this.warningMessage = false;
cartHelper.addToCart(this.product.id, this.variationId, amount, (response) => {
this.cartItems = response.data.attributes.items;
});
} else {
this.warningMessage = true;
}
},
So I want to pass this "this.cartItems" to the child component which is:
<template>
<div
class="dropdown-menu cart"
aria-labelledby="triggerId"
>
<div class="inner-cart">
<div v-for="item in cart" :key="item.product.id">
<div class="cart-items">
<div>
<strong>{{ item.product.name }}</strong>
<br/> {{ item.quantity }} x $45
</div>
<div>
<a class="remove" #click.prevent="removeProductFromCart(item.product)">Remove</a>
</div>
</div>
</div>
<hr/>
<div class="cart-items-total">
<span>Total: {{cartTotalPrice}}</span>
Clear Cart
</div>
<hr/>
<router-link :to="{name: 'order'}" class="btn button-secondary">Go To Cart</router-link>
</div>
</div>
</template>
<script>
export default {
computed: {
},
methods: {
}
};
</script>
So I am quite new in vue if you can help me with thi, I would be really glad.
Passing props is quite simple. If cartItems is what you wanΒ΄t to pass as a prop, you can do this:
<my-child-component :cartItems="cartItems"></my-child-component>
In this case you implemented your child as myChildComponent. You pass cartItems with :cartItems="cartItems" to it. In your child you do this:
props: {
cartItems: Object
}
Now you can use it with this.cartItems in your methods or {{cartItems}} in your themplate.
Vue.component('Child', {
template: `
<div class="">
<p>{{ childitems }}</p>
</div>
`,
props: ['childitems']
})
new Vue({
el: '#demo',
data() {
return {
items: []
}
},
methods: {
getItems() {
//your API call
setTimeout(() => {
this.items = [1, 2]
}, 2000);
}
}
})
Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<button #click="getItems">get data</button>
<Child v-if="items.length" :childitems="items" />
</div>
You can wait for response, and when you gate this.cartItems then render your child component with a v-if="this.cartItems.length" condition

Emit in vue does not upgrade property in parent component

The emit works, I can see that in the vue developer tool. But the property in the parent element does not upgrade.
Child Component:
<template>
<div>
<ul>
<li v-for="(option, index) in options" :key="index" #click="selectOption(index)">
{{ option }}
</li>
</ul>
</div>
</template>
<script>
export default {
name: "Dropdown",
props: {
options: {
type: Array,
},
},
data() {
return {
value: "",
}
},
methods: {
selectOption(id) {
this.value = this.options[id];
this.$emit("clickedOption", this.value);
}
}
}
</script>
Parent Component:
<button v-on:clickedOption="selectRole($event)">Select Role</button>
methods: {
selectRole(value) {
this.role = value.payload;
},
It seems that the function selectRole is not getting executed.
I had to give the parent element the emit function like this:
<Dropdown :options="roleOptions" v-show="dropdownToggle" #clickedOption="selectRole($event)"></Dropdown>

How to create a vue modal that sends user input to another component

I am trying to create a modal component that takes in user input, and upon saving that information, is displayed within another component. For example, a user is prompted to input their first and last name respectively in a modal component (Modal.vue). Once the user saves that data (a submit method on the modal), the data is displayed on another component (InputItem.vue).
Currently, I have a CreateEvent.vue component that houses the input elements, a modal.vue component that is the modal, an EventItem.vue component, that will display what is entered on once CreateEvent is executed, an EventsList.vue component that displays all the events that a user creates and finally, app.vue which houses the Modal and Events components.
I have been able to successfully get this CRUD functionality working without the modal component, but once I add the modal, I am getting confused.
If you could help lead me in the right direction, I would appreciate that!
Modal.vue
<template>
<transition name="modal-fade">
<div class="modal-backdrop">
<div
class="modal"
role="dialog"
aria-labelledby="modalTitle"
aria-describedby="modalDescription"
>
<header class="modal-header" id="modalTitle">
<slot name="header">
Create an Event
<button
type="button"
class="btn-close"
#click="close"
aria-label="Close modal"
>
x
</button>
</slot>
</header>
<section class="modal-body" id="modalDescription">
<slot name="body">
<div #keyup.enter="addTodo">
<input
type="text"
class="todo-input"
placeholder="What needs to be done"
v-model="newTodo"
/>
<input
type="text"
placeholder="add an emoji?"
v-model="newEmoji"
/>
</div>
<button #click="doneEdit">Create Event</button>
<button #click="cancelEdit">Cancel</button>
</slot>
</section>
<footer class="modal-footer">
<slot name="footer">
I'm the default footer!
<button
type="button"
class="btn-green"
#click="close"
aria-label="Close modal"
>
Close me!
</button>
</slot>
</footer>
</div>
</div>
</transition>
</template>
<script>
export default {
name: 'modal',
data() {
return {
newTodo: '',
newEmoji: '',
idForTodo: this.todos.length + 1
}
},
methods: {
close() {
this.$emit('close')
},
addTodo() {
if (this.newTodo.trim().length == 0) return
this.todos.push({
id: this.idForTodo,
title: this.newTodo,
emoji: this.newEmoji
})
this.newTodo = ''
this.newEmoji = ''
this.idForTodo++
}
}
}
</script>
CreateEvent.vue
<template>
<div #keyup.enter="addTodo">
<input
type="text"
class="todo-input"
placeholder="What needs to be done"
v-model="newTodo"
/>
<input type="text" placeholder="add an emoji?" v-model="newEmoji" />
</div>
</template>
<script>
export default {
props: {
todos: {
type: Array
}
},
data() {
return {
newTodo: '',
newEmoji: '',
idForTodo: this.todos.length + 1
}
},
methods: {
addTodo() {
if (this.newTodo.trim().length == 0) return
this.todos.push({
id: this.idForTodo,
title: this.newTodo,
emoji: this.newEmoji
})
this.newTodo = ''
this.newEmoji = ''
this.idForTodo++
}
}
}
</script>
EventItem.vue
<template>
<div class="todo-item">
<h3 class="todo-item--left">
<!-- <span v-if="!editing" #click="editTodo" class="todo-item--label">
{{ title }}
{{ emoji }}
</span> -->
<input
class="todo-item--edit"
type="text"
v-model="title"
#click="editTitle"
#blur="doneEdit"
/>
<input
class="todo-item--edit"
type="text"
v-model="emoji"
#click="editEmoji"
#blur="doneEdit"
/>
<!-- <button #click="doneEdit">Update</button>
<button #click="cancelEdit">Cancel</button> -->
</h3>
<button class="remove-item" #click="removeTodo(todo.id)">✘</button>
</div>
</template>
<script>
export default {
name: 'todo-item',
props: {
todo: {
type: Object,
required: true
}
},
data() {
return {
id: this.todo.id,
title: this.todo.title,
emoji: this.todo.emoji,
editing: this.todo.editing,
beforeEditCacheTitle: this.todo.title,
beforeEditCacheEmoji: this.todo.emoji
}
},
methods: {
editTitle() {
this.beforeEditCacheTitle = this.title
this.editing = true
},
editEmoji() {
this.beforeEditCacheEmoji = this.emoji
this.editing = true
},
doneEdit() {
if (this.title.trim() == '') {
this.title = this.beforeEditCacheTitle
}
if (this.emoji.trim() == '') {
this.emoji = this.beforeEditCacheEmoji
}
this.editing = false
this.$emit('finishedEdit', {
id: this.id,
title: this.title,
emoji: this.emoji,
editing: this.editing
})
},
cancelEdit() {
this.title = this.beforeEditCacheTitle
this.emoji = this.beforeEditCacheEmoji
this.editing = false
},
removeTodo(id) {
this.$emit('removedTodo', id)
}
}
}
</script>
Events.vue
<template>
<div>
<transition-group
name="fade"
enter-active-class="animated fadeInUp"
leave-active-class="animated fadeOutDown"
>
<EventItem
v-for="todo in todosFiltered"
:key="todo.id"
:todo="todo"
#removedTodo="removeTodo"
#finishedEdit="finishedEdit"
/>
</transition-group>
</div>
</template>
<script>
import EventItem from '#/components/EventItem'
export default {
components: {
EventItem
},
data() {
return {
filter: 'all',
todos: [
{
id: 1,
title: 'Eat sushi',
emoji: 'πŸ’΅',
editing: false
},
{
id: 2,
title: 'Take over world',
emoji: 'πŸ‘¨πŸ½β€πŸ’»',
editing: false
}
]
}
},
computed: {
todosFiltered() {
if (this.filter == 'all') {
return this.todos
}
}
},
methods: {
removeTodo(id) {
const index = this.todos.findIndex(item => item.id == id)
this.todos.splice(index, 1)
},
finishedEdit(data) {
const index = this.todos.findIndex(item => item.id == data.id)
this.todos.splice(index, 1, data)
}
}
}
</script>
app.vue
<template>
<div id="app" class="container">
<button type="button" class="btn" #click="showModal">
Create Event
</button>
<Modal v-show="isModalVisible" #close="closeModal" />
<Events />
</div>
</template>
<script>
import Events from './components/Events'
import Modal from './components/Modal'
export default {
name: 'App',
components: {
Events,
Modal
},
data() {
return {
isModalVisible: false
}
},
methods: {
showModal() {
this.isModalVisible = true
},
closeModal() {
this.isModalVisible = false
}
}
}
</script>
The modal component should emit the values instead of pushing it into the todos array. When it emits it, the parent component (App.vue) listens for the emitted items.
I would do something like this
Modal.vue
<template>
...
// header
<section class="modal-body" id="modalDescription">
<slot name="body">
<div #keyup.enter="addTodo">
...
</div>
<button #click="handleModalSubmit">Create Event</button>
...
//footer
...
</template>
<script>
export default {
...
data() {
...
},
methods: {
...,
handleModalSubmit() {
this.$emit('todos-have-been-submitted', this.todos);
},
addTodo() {
...
this.todos.push({
id: this.idForTodo,
title: this.newTodo,
emoji: this.newEmoji
})
...
}
}
}
</script>
App.vue
<template>
...
<Modal
#todos-have-been-submitted="handleTodoSubmission" //watch the 'todos-have-been-submitted" emission and trigger handleTodoSubmission method when the emission is detected
/>
<Events
:todos="todos" // pass todos as a prop to the Events component
/>
...
</template>
<script>
import Events from './components/Events'
import Modal from './components/Modal'
export default {
name: 'App',
components: {
Events,
Modal
},
data() {
return {
...,
todos: []
}
},
methods: {
...,
handleTodoSubmission(todos) {
this.todos = [...todos];
}
}
}
</script>

How can I periodically update my component in VueJS

I have a component in Vue that looks like this:
<template>
<div id="featured_top">
<i class="i-cancel close"></i>
<div v-for="item in toplist">
<div class="featured-item" v-lazy:background-image="poster(item)">
<a class="page-link" :href="url(item)" target="_blank">
<h4 class="type"> Featured Movie </h4>
<div class="title">{{ item.title }}</div>
</a>
</div>
</div>
</div>
</template>
<script>
const _ = require('lodash')
export default {
name: 'featured',
computed: {
toplist () {
return _.sampleSize(this.$store.state.toplist, 3)
}
},
methods: {
poster: function (item) {
return 'https://example.com/' + item.backdrop_path
},
url: function (item) {
return 'http://example.com/' + item.id
}
}
}
</script>
I choose three random items from the store hen rendering the component, iterate over and display then. However, this seems too static so I'd like periodically update the component so it randomises the items again.
I'm new to Vue2 - any ideas on what trivial bit I'm missing?
Your use-case is not completely clear to me but if you'd like to randomize with an interval. You could change your computation to a method and call this function with setInterval.
Something like in the demo below or this fiddle should work.
(In the demo I've removed the lazy loading of the image to reduce the complexity a bit.)
// const _ = require('lodash')
const testData = _.range(1, 10)
.map((val) => {
return {
title: 'a item ' + val
}
})
const store = new Vuex.Store({
state: {
toplist: testData
}
})
//export default {
const randomItems = {
name: 'featured',
template: '#tmpl',
computed: {
/*toplist () {
return _.sampleSize(this.$store.state.toplist, 3)
}*/
},
created() {
this.getToplist() // first run
this.interval = setInterval(this.getToplist, 2000)
},
beforeDestroy() {
if (this.interval) {
clearIntervall(this.interval)
this.interval = undefined
}
},
data() {
return {
interval: undefined,
toplist: []
}
},
methods: {
getToplist() {
this.toplist = _.sampleSize(this.$store.state.toplist, 3)
},
poster: function(item) {
return 'https://example.com/' + item.backdrop_path
},
url: function(item) {
return 'http://example.com/' + item.id
}
}
}
new Vue({
el: '#app',
template: '<div><random-items></random-items</div>',
store,
components: {
randomItems
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.1.1/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<div id="app">
</div>
<script type="text/template" id="tmpl">
<div id="featured_top">
<i class="i-cancel close"></i>
<div v-for="item in toplist">
<div class="featured-item" v-lazy:background-image="poster(item)">
<a class="page-link" :href="url(item)" target="_blank">
<h4 class="type"> Featured Movie </h4>
<div class="title">{{ item.title }}</div>
</a>
</div>
</div>
</div>
</script>

Laravel Vue.js fragment component

I have watched Jeffory's series on Vue.js and I'm practicing writing my own components using the vueify and browserify with gulp. Even after following along with the video I can't manage to get it to render properly. I keep getting this error.
TRY NUMBER ONE
Error:
Attribute "list" is ignored on component <alert> because the component is a fragment instance:
The view:
<div id = "app" class = "container">
<alert :list = "tasks"></alert>
</div>
The Componet:
<template>
<div>
<h1>My tasks
<span v-show = "remaining"> ( #{{ remaining }} )</span>
</h1>
<ul>
<li :class = "{ 'completed': task.completed }"
v-for = "task in list"
#click="task.completed = ! task.completed"
>
#{{ task.body }}
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['list'],
computed: {
remaining: function() {
return this.list.filter(this.inProgress).length;
}
},
methods: {
isCompleted: function(task) {
return task.completed;
},
inProgress: function(task) {
return ! this.isCompleted(task);
}
}
}
new Vue({
el: '#demo',
data: {
tasks: [
{ body: 'go to the store', completed: false },
{ body: 'go to the bank', completed: false },
{ body: 'go to the doctor', completed: true }
]
},
methods: {
toggleCompletedFor: function(task) {
task.completed = ! task.completed;
}
}
});
</script>
It gives me a link to read the Fragement Instance section in the documentation. What I understood was that if the template is composed of more than one top level element the component will be fragmented. So I took everything out of the template execpt the actual li tags. With this I still get the same error. What am missing?
Edited Template:
<li :class = "{ 'completed': task.completed }"
v-for = "task in list"
#click="task.completed = ! task.completed"
>
#{{ task.body }}
</li>
TRY NUMBER TWO
Same error
View
<div id ="app">
<alert>
<strong>Success!</strong> Your shit has been uploaded!
</alert>
<alert type = "success">
<strong>Success!</strong> Your shit has been uploaded!
</alert>
<alert type = "error">
<strong>Success!</strong> Your shit has been uploaded!
</alert>
</div>
Main.js
var Vue = require('vue');
import Alert from './componets/Alert.vue';
new Vue({
el: '#app',
components: { Alert },
ready: function() {
alert('Ready to go!');
}
});
Alert.Vue
<template>
<div>
<div :class ="alertClasses" v-show = "show">
<slot></slot>
<span class = "Alert_close" #click="show = false">X</span>
</div>
</div>
</template>
<script>
export default {
props: ['type'],
data: function() {
return {
show: true
};
},
computed: {
alertClasses: function () {
var type = this.type;
return{
"Alert": true,
"Alert--Success": type == "success",
"Alert--Error": type == "error"
}
}
}
}
</script>
Fresh re-install of the most curruent versions of node,gulp and vueify turned out to be the solution.

Categories

Resources