I have two files named Recursive.vue and Value.vue.
In the first instance Recursive is the parent. Mounting Recursive in Recursive goes great, same for mounting Value in Recursive and after that Value in Value.
But when I've mounted Value in Recursive and trying to mount Recursive in Value after that I get the following error:
[Vue warn]: Failed to mount component: template or render function not defined.
(found in component <recursive>)
How can I make my problem work?
This is what my files are looking like:
Recursive
<template>
<div class="recursive">
<h1 #click="toggle">{{comps}}</h1>
<div v-if="isEven">
Hello
<value :comps="comps"></value>
</div>
</div>
</template>
<script>
import Value from './Value.vue'
export default {
name: 'recursive',
components: {
Value
},
props: {
comps: Number
},
computed: {
isEven () {
return this.comps % 2 == 0;
}
},
methods: {
toggle () {
this.comps++;
}
}
}
</script>
Value
<template>
<div class="value">
<h1 #click="toggle">{{comps}}</h1>
<div v-if="isEven">
<recursive :comps="comps"></recursive>
</div>
</div>
</template>
<script>
import Recursive from './Recursive.vue'
export default {
name: 'value',
components: {
Recursive
},
props: {
comps: Number
},
computed: {
isEven () {
return this.comps % 2 == 0;
}
},
methods: {
toggle () {
this.comps++;
}
}
}
</script>
Mounter
<template>
<div class="mounter">
<h1>HI</h1>
<recursive :comps="comps"></recursive>
</div>
</template>
<script>
import Recursive from './Recursive'
export default {
name: 'mounter',
components: {
Recursive
},
data () {
return {
comps: 0
}
}
}
</script>
I had a similar problem before. The only way out was declaring the component as "global", because importing it in the component which actually required it never worked.
new Vue({
...
})
Vue.component('recursive', require('./Recursive'))
Then you can just use without importing:
// Mounted
<template>
<div class="mounter">
<h1>HI</h1>
<recursive :comps="comps"></recursive>
</div>
</template>
<script>
export default {
name: 'mounter',
data () {
return {
comps: 0
}
}
}
</script>
Related
In Vue2 I'm trying to access child components' data and then put into parent component's data without triggering an event. In the following example I want to save count:20 into parent component, please tell me if there's any mistake, thanks!
Child Component
<template>
<div></div>
</template>
<script>
export default {
data() {
return {
count: 20,
};
},
};
</script>
Parent Component
<template>
<div>
<child ref="child1"></child>
{{count}}
</div>
</template>
<script> import child from './child.vue'
export default {
components: {
child
},
data() {
return{
count:this.$refs.child1.count
}
},
}
</script>
warn message in VScode
Property 'count' does not exist on type 'Vue | Element | Vue[] | Element[]'.
Property 'count' does not exist on type 'Vue'.
warn message in browser
[Vue warn]: Error in data(): "TypeError: undefined is not an object (evaluating 'this.$refs.child1')"
Let me preface with I would recommend using the Vue framework as intended. So passing data from a child to the parent should be done with $emit or using a vuex store for centralized state management.
With that out of the way you will want to wait until the parent component is mounted to set the count data attribute.
Child
<template>
<div></div>
</template>
<script>
export default {
data() {
return {
count: 20,
};
},
};
</script>
Parent
<template>
<div>
<child ref="child1"></child>
{{ count }}
</div>
</template>
<script>
import Child from "./components/Child";
export default {
components: {
Child
},
data() {
return{
count: 0
}
},
mounted () {
this.count = this.$refs.child1.count
}
};
</script>
This will work, however it WILL NOT BE reactive. This can all be greatly simplified AND made reactive with the following changes:
Child
<template>
<div></div>
</template>
<script>
export default {
data() {
return {
count: 20,
};
},
watch: {
count (currentValue) {
this.$emit('update', currentValue);
}
},
beforeMount () {
this.$emit('update', this.count)
}
};
</script>
Parent
<template>
<div>
<child #update="count = $event"></child>
{{ count }}
</div>
</template>
<script>
import Child from "./components/Child";
export default {
components: {
Child
},
data() {
return{
count: 0
}
}
};
</script>
Quick link to show a working example: https://codesandbox.io/s/interesting-kalam-et0b3?file=/src/App.vue
I am learning $emit in Vue JS, I decided to create a value called counter in the child component then increment by one when the button is clicked, but I decided to write all the logic in the parent component using $emit
But every time I click on the button, the value does not increase although the method works
LifeCycles.vue
<template>
<div>
<p>{{counter}}</p>
<button #click="add">Click me</button>
</div>
</template>
<script>
export default {
data() {
return {
counter: 0,
};
},
methods: {
add() {
this.$emit('updated', this.counter)
}
},
};
</script>
HeadlineLifeCycle.vue
<template>
<div>
<LifeCycles #updated="usefulMethod" />
</div>
</template>
<script>
import LifeCycles from "./LifeCycles.vue";
export default {
components: {
LifeCycles,
},
methods: {
usefulMethod: function(counter) {
console.log(counter++)
}
}
};
</script>
This is because you're not incrementing count in the child component where it's placed in its data:
const lifecycles = Vue.component('lifecycles', {
template: "#lifecycles",
data() { return { counter: 0 } },
methods: {
add() { this.$emit('updated', ++this.counter); } // fix
}
});
new Vue({
el: "#headlinelifecycle",
components: { lifecycles },
methods: {
usefulMethod: function(counter) { console.log(counter); }
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template id="lifecycles">
<div>
<p>{{counter}}</p>
<button #click="add">Click me</button>
</div>
</template>
<div id="headlinelifecycle"><LifeCycles #updated="usefulMethod" /></div>
If you want to control LifeCycles from the parent state:
const lifecycles = Vue.component('lifecycles', {
template: "#lifecycles",
props: ['counter'],
methods: {
add() { this.$emit('updated', this.counter+1); }
}
});
new Vue({
el: "#headlinelifecycle",
components: { lifecycles },
data() { return { counter: 0 } },
methods: {
usefulMethod: function(counter) {
this.counter = counter;
console.log(this.counter);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template id="lifecycles">
<div>
<p>{{counter}}</p>
<button #click="add">Click me</button>
</div>
</template>
<div id="headlinelifecycle">
<LifeCycles #updated="usefulMethod" :counter="counter" />
</div>
The line
this.$emit('updated', this.counter)
is not emitting this.counter reference, so any time you click on the button, you actually are emmiting the counter initial value which is 0.
So, if you really need to do all the logic in the parent component, you have to define the counter variable in parent component:
lifecycle.vue
<template>
<div>
<p>{{counter}}</p>
<button #click="$emit('clicked')">Click me</button>
</div>
</template>
HeadlineLifeCycle.vue
<template>
<div>
<LifeCycles #clicked="increase" />
</div>
</template>
<script>
import LifeCycles from "./LifeCycles.vue";
export default {
components: {
LifeCycles,
},
data() {
return {
counter: 0,
};
},
methods: {
increase: function() {
console.log(this.counter++)
}
}
};
</script>
You also can pass a variable to the lifecycle.vue as model and manage its value in lifecycle component.
I have a simple component:
<template>
<div id="search__index_search-form">
<input :foo-id="fooId" #keyup.enter="findFoos()" type="text" :value="keyword" #input="updateKeyword"
placeholder="Search for a foo">
<button #click="findFoos()">Search!</button>
{{fooId}}
</div>
</template>
<script>
import {mapState} from "vuex";
export default {
computed: mapState({
keyword: state => state.search.keyword
}),
data: function () {
return {fooId: "all"};
},
methods: {
updateKeyword(e) {
this.$store.commit("setSearchKeyword", e.target.value);
},
findFoos() {
this.$store.dispatch("findFoos");
}
}
};
</script>
I am calling it from nuxt page:
<template>
<searchbar v-bind:fooId="500"/>
</template>
<script>
import searchBar from "~/components/search-bar.vue";
export default {
components: {
'searchbar': searchBar
}
};
</script>
This results in:
<div id="search__index_search-form" fooid="500"><input shop-id="all" type="text" placeholder="Search for a foo"><button>Search!</button>
all
</div>
Question is, why is fooId bound to "div.search__index_search-form" and not to input? And how come {{fooId}} results in "all" (default state), and not "500"?
fooId is rendered on div#search__index_search-form because you do not declare fooId as a property of the component. Vue's default behavior is to render undeclared properties on the root element of the component.
You need to declare fooId as a property.
export default {
props: {
fooId: {type: String, default: "all"}
},
computed: mapState({
keyword: state => state.search.keyword
}),
methods: {
updateKeyword(e) {
this.$store.commit("setSearchKeyword", e.target.value);
},
findProducts() {
this.$store.dispatch("findFoos");
}
}
};
I'm not sure what you are really trying to accomplish though.
<input :foo-id="fooId" ... >
That bit of code doesn't seem to make any sense.
I have a simple application which need to render 2 components dynamically.
Component A - needs to have onClick event.
Component B - needs to have onChange event.
How is it possible to dynamically attach different events to component A/B?
<template>
<component v-bind:is="currentView">
</component>
</template>
<script>
import A from '../components/a.vue'
import B from '../components/b.vue'
export default {
data: function () {
return {
currentView: A
}
},
components: { A, B }
}
</script>
Here is a solution for a little more complicated and realistic use case. In this use case you have to render multiple different components using v-for.
The parent component passes an array of components to create-components. create-components will use v-for on this array, and display all those components with the correct event.
I'm using a custom directive custom-events to achieve this behavior.
parent:
<template>
<div class="parent">
<create-components :components="components"></create-components>
</div>
</template>
<script>
import CreateComponents from '#/components/CreateComponents'
import ComponentA from '#/components/ComponentA'
import ComponentB from '#/components/ComponentB'
export default {
name: 'parent',
data() {
return {
components: [
{
is: ComponentA,
events: {
"change":this.componentA_onChange.bind(this)
}
},
{
is: ComponentB,
events: {
"click":this.componentB_onClick.bind(this)
}
}
]
}
},
methods: {
componentA_onChange() {
alert('componentA_onChange');
},
componentB_onClick() {
alert('componentB_onClick');
}
},
components: { CreateComponents }
};
</script>
create-components:
<template>
<div class="create-components">
<div v-for="(component, componentIndex) in components">
<component v-bind:is="component.is" v-custom-events="component.events"></component>
</div>
</div>
</template>
<script>
export default {
name: 'create-components',
props: {
components: {
type: Array
}
},
directives: {
CustomEvents: {
bind: function (el, binding, vnode) {
let allEvents = binding.value;
if(typeof allEvents !== "undefined"){
let allEventsName = Object.keys(binding.value);
allEventsName.forEach(function(event) {
vnode.componentInstance.$on(event, (eventData) => {
allEvents[event](eventData);
});
});
}
},
unbind: function (el, binding, vnode) {
vnode.componentInstance.$off();
}
}
}
}
</script>
You don't have to dynamically add them.
<component v-bind:is="currentView" #click="onClick" #change="onChange">
If you want to be careful you can bail in the handler of the currentView is not correct.
methods: {
onClick(){
if (this.currentView != A) return
// handle click
},
onChange(){
if (this.currentView != B) return
// handle change
}
}
I've got a component that looks like this:
<template>
<div>
<pagination class="center" :pagination="pagination" :callback="loadData" :options="paginationOptions"></pagination>
</div>
</template>
<script>
import Pagination from 'vue-bootstrap-pagination';
export default {
components: { Pagination },
props: ['pagination', 'loadData'],
data() {
return {
paginationOptions: {
offset: 5,
previousText: 'Terug',
nextText: 'Volgende',
alwaysShowPrevNext: false
}
}
}
}
</script>
In another component I use that ^:
<template>
<pagination :pagination="pagination" :callback="loadData" :options="paginationOptions"></pagination>
</template>
<script>
export default {
loadData() {
this.fetchMessages(this.pagination.current_page);
}
//fetchMessages
}
</script>
But I receive the error:
Invalid prop: type check failed for prop "callback". Expected Function, got Undefined.
(found in component <pagination>)
Is it not possible in Vue.js 2.0 to pass a callback?
I think your second component may not be written accurately, your loadData callback should be in methods:
<template>
<pagination :pagination="pagination" :callback="loadData" :options="paginationOptions"></pagination>
</template>
<script>
export default {
methods: {
loadData() {
this.fetchMessages(this.pagination.current_page);
}
}
}
</script>
App.vue
<template>
<div>
<pre>{{ request }}</pre>
<pagination #callback="loadData"></pagination>
</div>
</template>
<script>
import Pagination from './Pagination.vue'
export default {
name: 'App',
components: { Pagination },
data() {
return {
request: {}
}
},
methods: {
loadData(request) {
this.request = request
}
}
}
</script>
Pagination.vue:
<template>
<div>
<button #click="$emit('callback', { currentPage: 10, whatEver: 7 })">call it back</button>
</div>
</template>
<script>
export default {
name: 'Pagination'
}
</script>
https://codesandbox.io/embed/8xyy4m9kq8