I just started using Vue and I have a very simple issue that I just can't get to work! I'm trying to create a mounted event that runs a method with a specific parameter inside it to alter the "show" value of an element. here is the code:
export default {
data(){
return {
one: false,
}
},
methods: {
show: function(el) {
this.el = true;
}
},
mounted(){
this.show(this.one)
}
}
I want "el" to be just a generic placeholder for whatever "data" name is passed into the method. in the future I may not only have "one" but also "two", "three" and "four". I want the "show" method to be able to take in any reference to one of these 4 options and change its value from false to true.
in the show method, I get the error "'el' is defined but never used."
the only solution I've come to is to do an if method "if this.one === el{...}" but that kind of defeats the purpose. any help would be appreciated
You can do something like this:
export default {
data(){
return {
one: false,
two: false
}
},
methods: {
doSomething(el) {
this[el] = true;
}
},
mounted(){
//Also works with vue props!
this.doSomething('one')
this.doSomething('two')
}
}
But if the function is more complex you should build a componet for that. Thats the vue way.
new Vue({
el: '#editor',
data: {
el: false,
item : ''
},
computed: {
},
methods: {
show (passedValue, item) {
this.item = item
this.el = passedValue
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/marked#0.3.6"></script>
<script src="https://unpkg.com/lodash#4.16.0"></script>
<div id="editor">
<div id="div1" v-if="el===true && item =='div-1'" class="show">
div1 displayed
</div>
<div id="div-2" v-if="el===true && item =='div-2'" class="show">
div2 displayed
</div>
<button v-on:click="show(true, 'div-1')">show div1</button>
<button v-on:click="show(false, 'div-1')">hide div1</button>
<button v-on:click="show(true, 'div-2')">show div2</button>
<button v-on:click="show(false, 'div-2')">hide div2</button>
</div>
export default {
data(){
return {
one: false,
}
},
methods: {
show(bol) {
this.one = bol;
}
},
mounted(){
this.show(this.one)
}
}
Use above code it would work.
I'm adding a way for the parent App.vue tell all child components to close every modal you have open and for any given child to tell the parent to hide the overlay if someone clicks on the main app div. So for example if the services page has a modal open to view some details, an overlay will be active that is set in the parent App.vue component, and if I click anywhere outside of the modal, the modal will close and the child will tell the parent to close the overlay. I have it setup this way so that it's something globally available and not isolated to a single component.
<template>
<div id="app" v-cloak :class="{'overlay-layer' : overlay.active}" v-on:click="close($event)">
<Header/>
<transition>
<router-view v-on:overlay="overlay.active = $event" :closeAllModals="overlay.close"/>
</transition>
<Footer/>
</div>
</template>
<script>
import Header from '#/components/header/Header.vue';
import Footer from '#/components/footer/Footer.vue';
export default {
components: {
Header,
Footer
},
props: {
closeAllModals: Boolean
},
data: function() {
return {
overlay: { active: false, close: false }
};
},
methods: {
close(e) {
if (this.overlay.active && e.toElement.id === 'app') {
this.overlay = {
active: false,
close: true
}
}
}
}
};
</script>
The problem is that this only executes once, so for example in the services page I have:
import Header from '#/components/header/Header.vue';
import Footer from '#/components/footer/Footer.vue';
export default {
name: 'services',
components: {
Header,
Footer
},
props: {
closeAllModals: Boolean
},
data: function() {
return {
overlay: false,
activeMember: Object,
};
},
methods: {
setActiveMember(member, open) {
this.activeMember = member;
if (open) {
this.activeMember.active = true;
this.overlay = true;
} else {
this.activeMember.active = false;
this.overlay = false;
}
this.$emit('overlay', this.overlay);
this.$forceUpdate();
},
watch: {
closeAllModals: function() {
this.activeMember.active = false;
this.overlay = false;
this.$forceUpdate();
console.log('runs once');
}
}
};
So this works, but only works the first time. The prop only sends the updated value to the child only once. I've tried watching the prop in the child and using forceUpdate too but it isn't working. How do I make this run every single time?
A global event bus could help when components have to talk to each other across different parent/child levels. Below is a good write up on that:
https://alligator.io/vuejs/global-event-bus
Note: but be sure to use it only when necessary and remove the listeners in beforeDestroy life cycle of the component
I have a simple component that uses mixin that's shared across multiple components with similar functionality.
When I run it I seem to be getting
Property or method "activeClass" is not defined on the instance but
referenced during render.
Here's my mixin
<script>
export default {
data() {
return {
opened: false,
identity: ''
}
},
computed: {
activeClass() {
return {
active: this.opened
};
}
},
created() {
window.EventHandler.listen(this.identity + '-toggled', opened => this.opened = opened);
},
methods: {
toggle() {
window.EventHandler.fire('toggle-' + this.identity);
}
}
}
</script>
and my component
<template>
<span class="pointer" :class="activeClass" #click="toggle"><i class="fas fa-search"></i></span>
</template>
<script>
import Trigger from '../../mixins/Trigger';
export default {
data() {
return {
mixins: [Trigger],
data() {
return {
identity: 'language'
}
}
}
}
}
</script>
For some reason I cannot seem to be able to access activeClass computed property from within the component. Any idea why is this happening?
Try to move mixin to components main scope. Not in data function rerurn
I'm a bit confused about how to change properties inside components, let's say I have the following component:
{
props: {
visible: {
type: Boolean,
default: true
}
},
methods: {
hide() {
this.visible = false;
}
}
}
Although it works, it would give the following warning:
Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "visible"
(found in component )
Now I'm wondering what the best way to handle this is, obviously the visible property is passed in when created the component in the DOM: <Foo :visible="false"></Foo>
Referencing the code in your fiddle
Somehow, you should decide on one place for the state to live, not two. I don't know whether it's more appropriate to have it just in the Alert or just in it's parent for your use case, but you should pick one.
How to decide where state lives
Does the parent or any sibling component depend on the state?
Yes: Then it should be in the parent (or in some external state management)
No: Then it's easier to have it in the state of the component itself
Kinda both: See below
In some rare cases, you may want a combination. Perhaps you want to give both parent and child the ability to hide the child. Then you should have state in both parent and child (so you don't have to edit the child's props inside child).
For example, child can be visible if: visible && state_visible, where visible comes from props and reflects a value in the parent's state, and state_visible is from the child's state.
I'm not sure if this is the behavour that you want, but here is a snippet. I would kinda assume you actually want to just call the toggleAlert of the parent component when you click on the child.
var Alert = Vue.component('alert', {
template: `
<div class="alert" v-if="visible && state_visible">
Alert<br>
<span v-on:click="close">Close me</span>
</div>`,
props: {
visible: {
required: true,
type: Boolean,
default: false
}
},
data: function() {
return {
state_visible: true
};
},
methods: {
close() {
console.log('Clock this');
this.state_visible = false;
}
}
});
var demo = new Vue({
el: '#demo',
components: {
'alert': Alert
},
data: {
hasAlerts: false
},
methods: {
toggleAlert() {
this.hasAlerts = !this.hasAlerts
}
}
})
.alert {
background-color: #ff0000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo" v-cloak>
<alert :visible="hasAlerts"></alert>
<span v-on:click="toggleAlert">Toggle alerts</span>
</div>
According to the Vue.js component doc:
When the parent property updates, it will flow down to the child, but not the other way around. So, how do we communicate back to the parent when something happens? This is where Vue’s custom event system comes in.
Use $emit('my-event) from the child to send an event to the parent. Receive the event on the child declaration inside the parent with v-on:my-event (or #my-event).
Working example:
// child
Vue.component('child', {
template: '<div><p>Child</p> <button #click="hide">Hide</button></div>',
methods: {
hide () {
this.$emit('child-hide-event')
}
},
})
// parent
new Vue({
el: '#app',
data: {
childVisible: true
},
methods: {
childHide () {
this.childVisible = false
},
childShow () {
this.childVisible = true
}
}
})
.box {
border: solid 1px grey;
padding: 16px;
}
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<div id="app" class="box">
<p>Parent | childVisible: {{ childVisible }}</p>
<button #click="childHide">Hide</button>
<button #click="childShow">Show</button>
<p> </p>
<child #child-hide-event="childHide" v-if="childVisible" class="box"></child>
</div>
If the prop is only useful for this child component, give the child a prop like initialVisible, and a data like mutableVisible, and in the created hook (which is called when the component's data structure is assembled), simply this.mutableVisible = this.initialVisible.
If the prop is shared by other children of the parent component, you'll need to make it the parent's data to make it available for all children. Then in the child, this.$emit('visibleChanged', currentVisible) to notify the parent to change visible. In parent's template, use <ThatChild ... :visibleChanged="setVisible" ...>. Take a look at the guide: https://v2.vuejs.org/v2/guide/components.html
After a read of your latest comments it seems that you are concerned about having the logic to show/hide the alerts on the parent. Therefore I would suggest the following:
parent
# template
<alert :alert-visible="alertVisible"></alert>
# script
data () {
alertVisible: false,
...
},
...
Then on the child alert you would $watch the value of the prop and move all logic into the alert:
child (alert)
# script
data: {
visible: false,
...
},
methods: {
hide () {
this.visible = false
},
show () {
this.visible = true
},
...
},
props: [
'alertVisible',
],
watch: {
alertVisible () {
if (this.alertVisible && !this.visible) this.show()
else if (!this.alertVisible && this.visible) this.hide()
},
...
},
...
To help anybody, I was facing the same issue. I just changed my var that was inside v-model="" from props array to data. Remember the difference between props and data, im my case that was not a problem changing it, you should weight your decision.
E.g.:
<v-dialog v-model="dialog" fullscreen hide-overlay transition="dialog-bottom-transition">
Before:
export default {
data: function () {
return {
any-vars: false
}
},
props: {
dialog: false,
notifications: false,
sound: false,
widgets: false
},
methods: {
open: function () {
var vm = this;
vm.dialog = true;
}
}
}
After:
export default {
data: function () {
return {
dialog: false
}
},
props: {
notifications: false,
sound: false,
widgets: false
},
methods: {
open: function () {
var vm = this;
vm.dialog = true;
}
}
}
Maybe it looks like on hack and violates the concept of a single data source, but its work)
This solution is creating local proxy variable and inherit data from props. Next work with proxy variable.
Vue.component("vote", {
data: function() {
return {
like_: this.like,
dislike_: this.dislike,
}
},
props: {
like: {
type: [String, Number],
default: 0
},
dislike: {
type: [String, Number],
default: 0
},
item: {
type: Object
}
},
template: '<div class="tm-voteing"><span class="tm-vote tm-vote-like" #click="onVote(item, \'like\')"><span class="fa tm-icon"></span><span class="tm-vote-count">{{like_}}</span></span><span class="tm-vote tm-vote-dislike" #click="onVote(item, \'dislike\')"><span class="fa tm-icon"></span><span class="tm-vote-count">{{dislike_}}</span></span></div>',
methods: {
onVote: function(data, action) {
var $this = this;
// instead of jquery ajax can be axios or vue-resource
$.ajax({
method: "POST",
url: "/api/vote/vote",
data: {id: data.id, action: action},
success: function(response) {
if(response.status === "insert") {
$this[action + "_"] = Number($this[action + "_"]) + 1;
} else {
$this[action + "_"] = Number($this[action + "_"]) - 1;
}
},
error: function(response) {
console.error(response);
}
});
}
}
});
use component and pass props
<vote :like="item.vote_like" :dislike="item.vote_dislike" :item="item"></vote>
I wonder why it is missed by others when the warning has a hint
Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "visible" (found in component )
Try creating a computed property out of the prop received in the child component as
computed: {
isVisible => this.visible
}
And use this computed in your child component as well as to emit the changes to your parent.
I have a component which adds a class for an animation after 5 seconds
export default Ember.Component.extend({
tagName: 'div',
classNames: ['gears'],
isVisible: false,
_startTimer: Ember.on('didInsertElement', function () {
var _this = this;
this._visibleTimer = Ember.run.later(this, function () {
_this._visibleTimer = null;
_this.set('isVisible', true);
}, 5000);
}),
_endTimer: Ember.on('willDestroyElement', function () {
if (this._visibleTimer) {
Ember.run.cancel(this, this._visibleTimer);
}
})
});
<i class="fa fa-cog fa-fw big {{if isVisible 'fa-counter'}}"></i>
My Problem is that in a specific a Route i need to set isVisible: true
I know that in Ember we can access by the route to the controller by setUpController but what if i want to set isVisible: true for a Component?
If this is not possible , are there other ways to achieve it? Maybe inside the component itself?
This sounds like a problem that could be resolved through Ember.Service. You can go about it in a couple ways, but the more straightforward might be to inject the service into the component and bind isVisible.
Something like:
export default Ember.Service.extend({
isVisible: false
});
export default Ember.Component.extend({
visibility: Ember.inject.service(),
isVisible: Ember.computed.alias('visibility.isVisible')
});
export default Ember.Route.extend({
visibility: Ember.inject.service(),
afterModel() {
this.set('visibility.isVisible', true);
}
});