How to listen on all component events? - vuejs2

The grid component grid.js:
<template>
<div class="grid">
...
<component v-for="c in cells" :is="c.componentName"></component>
</div>
</template>
<script>
export default {
props: {
cells: { type: Array, required: true }
}
methods: {
// the idea what I need
reEmitAllCellComponentEventWithPrefix($event) {
// add prefix
this.$emit("cell-" + $event.name, $event.data);
}
}
}
</script>
The base-cell component base-cell.js (define common cell props and methods):
export default {
props: ['componentName', 'columnIndex', 'rowIndex', 'cellData', ...],
...
}
The custom-cell component custom-cell.js (all extend from base-cell component, register global):
<template>
<dom ...>
</template>
<script>
import baseCell from "./base-cell"
export default {
extends: baseCell,
props: {
componentName: '...',
customProp1: '...',
...
},
watch: {
// a custom event example
customProp1(){
this.$emit('custom-event1', ...)
}
},
...
}
</script>
All the cell components has its own custom events, maybe any event-name.
The usage:
// dom
<div id="app">
<grid :cells="cells" #cell-custom-event1="customCellEventHandler"></grid>
</div>
// js
import grid from "./grid"
new Vue({
el: '#app',
data: { cells: ... },
method: {
customCellEventHandler($event){
...
}
},
...
})
I wanna user can listen on cell component's custom event with prefix cell- when use grid component. How can I make this work?

You can do it like this:
<template>
<div class="row">
<component v-for="c in cells" :is="c.componentName" #click="onClick(c.name, c.data)"></component>
</div>
</template>
<script>
export default {
props: {
cells: { type: Array, required: true }
}
methods: {
onClick(name, data) {
this.$emit("cell-" + name, data);
}
}
}
</script>
Basically when you look through the cells and create the elements, you add a click event for each cell and add whatever parameters you want, and use them to emit the event.
If you also need the "event" data you can add $event in #click="onClick(c.name, c.data)" like this #click="onClick(c.name, c.data, $event)" and then you can add on the method the respective paramater onClick(name, data, e)
I hope this was what you were looking for.

Related

Vue pass data from compontent 1 to a method in component 2

I have a parent component and a childcomponent.
In my parent component I call a simple childcomponent-method to save an email to the email variable. But the variable email does not change.
My Parentcomponent:
import ChildComponent from "./ChildComponent";
export default {
components: {ChildComponent},
methods: {
openDocument(d) {
ChildComponent.methods.saveEmail('new#example.com');
}
}
My Childcomponent:
<template>
<div>
Email: {{ email }}
</div>
</template>
<script>
export default {
data: function () {
return {
email: ''
}
},
methods: {
saveEmail(email) {
this.email = email; // this does NOT change my email variable
}
}
}
</script>
Why my email variable does not change? How can I change this variable?
In vue it is not work like that. You have to use Probs:
Parent :
<template>
<div class="container">
<child-component :email ="email"></child-component> // NEW HERE
</div>
</template>
<script>
import ChildComponent from "./ChildComponent";
module.exports = {
data: function () {
return {
email:''
}
},
methods: {
openDocument(d) {
this.email = "example#gmil.com"
}
},
}
</script>
Child component:
<template>
<div class="container">
<h1>Profile Form Component</h1>
</div>
</template>
<script>
module.exports = {
module.exports = {
props: ['email'], //NEW HERE
created: function () {
console.log(this.email) //prints out an empty string
}
}
</script>
ATTENTION
As you I added 2 comment NEW HERE in the code , these 2 lines are really important for what you wanna do.
The code that I giving you is an example (not a complete answer) , Probs is the solution of what you asked for.
Hope it Helps <3.
The ChildComponent variable only holds the recipe for creating components of this type - but it does not hold your actual component. Your actual component lives inside your template - you have to add a ref attribute to it (e.g. <custom-component ref="custom" ... />) and then reference it like this.$refs.custom.saveEmail()

Element UI dialog component can open for the first time, but it can't open for the second time

I'm building web app with Vue, Nuxt, and Element UI.
I have a problem with the Element dialog component.
It can open for the first time, but it can't open for the second time.
This is the GIF about my problem.
https://gyazo.com/dfca3db76c75dceddccade632feb808f
This is my code.
index.vue
<template>
<div>
<el-button type="text" #click="handleDialogVisible">click to open the Dialog</el-button>
<modal-first :visible=visible></modal-first>
</div>
</template>
<script>
import ModalFirst from './../components/ModalFirst.vue'
export default {
components: {
'modal-first': ModalFirst
},
data() {
return {
visible: false,
};
},
methods: {
handleDialogVisible() {
this.visible = true;
}
}
}
</script>
ModalFirst.vue
<template>
<el-dialog
title="Tips"
:visible.sync="visible"
width="30%"
>
<span>This is a message</span>
<span slot="footer" class="dialog-footer">
<a>Hello</a>
</span>
</el-dialog>
</template>
<script>
export default {
props: [ 'visible' ]
}
</script>
And I can see a warning message on google chrome console after closing the dialog.
The warning message is below.
webpack-internal:///./node_modules/vue/dist/vue.runtime.esm.js:620 [Vue warn]: 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
---> <ModalFirst> at components/ModalFirst.vue
<Pages/index.vue> at pages/index.vue
<Nuxt>
<Layouts/default.vue> at layouts/default.vue
<Root>
This is the screenshot of the warning message.
https://gyazo.com/83c5f7c5a8e4d6816c35b3116c80db0d
In vue , using directly to prop value is not allowed . Especially when your child component will update that prop value , in my option if prop will be use
for display only using directly is not a problem .
In your code , .sync will update syncronously update data so I recommend to create local data.
ModalFirst.vue
<el-dialog
title="Tips"
:visible.sync="localVisible"
width="30%"
>
<script>
export default {
props: [ 'visible' ],
data: function () {
return {
localVisible: this.visible // create local data using prop value
}
}
}
</script>
If you need the parent visible property to be updated, you can create your component to leverage v-model:
ModalFirst.vue
<el-dialog
title="Tips"
:visible.sync="localVisible"
width="30%"
>
<script>
export default {
props: [ 'value' ],
data() {
return {
localVisible: null
}
},
created() {
this.localVisible = this.value;
this.$watch('localVisible', (value, oldValue) => {
if(value !== oldValue) { // Optional
this.$emit('input', value); // Required
}
});
}
}
</script>
index.vue
<template>
<div>
<el-button type="text" #click="handleDialogVisible">click to open the Dialog</el-button>
<modal-first v-model="visible"></modal-first>
</div>
</template>
<script>
import ModalFirst from './../components/ModalFirst.vue'
export default {
components: {
'modal-first': ModalFirst
},
data() {
return {
visible: false,
};
},
methods: {
handleDialogVisible() {
this.visible = true;
}
}
}
</script>
v-model is basically a shorthand for :value and #input
https://v2.vuejs.org/v2/guide/forms.html#Basic-Usage
Side-note:
You can also import your component like so:
components: { ModalFirst },
as ModalFirst will be interpreted as modal-first as well by Vue.js

Vuejs build/render component inside a method and output into template

I have a string (example, because it's an object with many key/values, want to loop and append to htmloutput) with a component name. Is it possible to render/build the component inside a method and display the html output?
Is that possible and how can i achieve that?
<template>
<div v-html="htmloutput"></div>
</template>
<script>
export default {
component: {
ComponentTest
},
data() {
return {
htmloutput: ''
}
},
methods:{
makeHtml(){
let string = 'component-test';//ComponentTest
//render the ComponentTest directly
this.htmloutput = ===>'HERE TO RENDER/BUILD THE COMPONENTTEST'<==
}
},
created(){
this.makeHtml();
}
</script>
You might be looking for dynamic components:
https://v2.vuejs.org/v2/guide/components-dynamic-async.html
Example:
<template>
<component :is="changeableComponent">
</component>
</template>
<script>
import FirstComponent from '#/views/first';
import SecondComponent from '#/views/second';
export default {
components: {
FirstComponent, SecondComponent
},
computed: {
changeableComponent() {
// Return 'first-component' or 'second-component' here which corresponds
// to one of the 2 included components.
return 'first-component';
}
}
}
</script>
Maybe this will help - https://forum.vuejs.org/t/how-can-i-get-rendered-html-code-of-vue-component/19421
StarRating is a sample Vue component. You can get it HTML code by run:
new Vue({
...StarRating,
parent: this,
propsData: { /* pass props here*/ }
}).$mount().$el.outerHTML
in Your method. Remember about import Vue from 'vue'; and of course import component.
What you're trying to do really isn't best practice for Vue.
It's better to use v-if and v-for to conditionally render your component in the <template> section.
Yes you can use the render function for that here is an example :
Vue.component('CompnentTest', {
data() {
return {
text: 'some text inside the header'
}
},
render(createElement) {
return createElement('h1', this.text)
}
})
new Vue({
el: '#app',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<Compnent-test />
</div>
Or :
if you are using Vue-cli :
on your componentTest component :
export default {
render(createElement) {
return createElement('h1', 'sometext')
}
// Same as
// <template>
// <h1>sometext</h1>
// </template>
//
}
and on your root element (App.vue as default) :
export default {
....
component: {
ComponentTest
}
}
<template>
<div>
....
<Component-test />
</div>
</template>
example : codesandbox
you can read more about
Render Functions & JSX

vue.js wrapping components which have v-models

I have a 3rd party input component (a vuetify v-text-field).
For reasons of validation i prefer to wrap this component in my own.
my TextField.vue
<template>
<v-text-field
:label="label"
v-model="text"
#input="onInput"
#blur="onBlur"
:error-messages="this.getErrors(this.validation, this.errors)"
></v-text-field>
</template>
<script>
import VTextField from "vuetify/es5/components/VTextField";
import {vuelidateErrorsMixin} from '~/plugins/common.js';
export default {
name: "TextField",
props: ['label', 'value', 'validation', 'errors'],
mixins: [vuelidateErrorsMixin], //add vuelidate
data: function() {
return {
'text': this.value
}
},
components: {
VTextField
},
methods : {
onInput: function(value) {
this.$emit('input', value);
this.validation.$touch();
},
onBlur: function() {
this.validation.$touch();
}
},
watch: {
value: {
immediate: true,
handler: function (newValue) {
this.text = newValue
}
}
}
}
</script>
which is used in another component
<template>
...
<TextField v-model="personal.email" label="Email"
:validation="$v.personal.email" :errors="[]"/>
...
</template>
<script>
...imports etc.
export default { ...
data: function() {
return {
personal: {
email: '',
name: ''
}
}
},
components: [ TextField ]
}
</script>
This works fine but i wonder if there is a much more cleaner approach than to replicate the whole v-model approach again. As now my data is duplicated in 2 places + all the extra (non needed) event handling...
I just want to pass the reactive data directly through to the v-text-field from the original temlate. My TextField doesn't actually need access to that data at all - ONLY notified that the text has changed (done via the #input, #blur handlers). I do not wish to use VUEX as this has it's own problems dealing with input / forms...
Something more close to this...
<template>
<v-text-field
:label="label"
v-model="value" //?? SAME AS 'Mine'
#input="onNotify"
#blur="onNotify"
:error-messages="this.getErrors(this.validation, this.errors)"
></v-text-field>
</template>
<script>
import VTextField from "vuetify/es5/components/VTextField";
import {vuelidateErrorsMixin} from '~/plugins/common.js';
export default {
name: "TextField",
props: ['label', 'validation', 'errors'], //NO VALUE HERE as cannot use props...
mixins: [vuelidateErrorsMixin], //add vuelidate
components: {
VTextField
},
methods : {
onNotify: function() {
this.validation.$touch();
}
},
}
</script>
I cannot find anything that would do this.
Using props + v-model wrapping is what i do.
You need to forward the value prop down to the wrapped component, and forward the update event back up (see https://v2.vuejs.org/v2/guide/components.html#Using-v-model-on-Components for more details):
<template>
<wrapped-component
:value='value'
#input="update"
/>
</template>
<script>
import wrappedComponent from 'wrapped-component'
export default {
components: { 'wrapped-component': wrappedComponent },
props: ['value'],
methods: {
update(newValue) { this.$emit('input', newValue); }
}
}
</script>
Somewhere else:
<my-wrapping-component v-model='whatever'/>
I've create a mixin to simplify wrapping of a component.
You can see a sample here.
The mixin reuse the same pattern as you with "data" to pass the value and "watch" to update the value during a external change.
export default {
data: function() {
return {
dataValue: this.value
}
},
props: {
value: String
},
watch: {
value: {
immediate: true,
handler: function(newValue) {
this.dataValue = newValue
}
}
}
}
But on the wraping component, you can use "attrs" and "listeners" to passthrough all attributes and listener to your child component and override what you want.
<template>
<div>
<v-text-field
v-bind="$attrs"
solo
#blur="onBlur"
v-model="dataValue"
v-on="$listeners" />
</div>
</template>
<script>
import mixin from '../mixins/ComponentWrapper.js'
export default {
name: 'my-v-text-field',
mixins: [mixin],
methods: {
onBlur() {
console.log('onBlur')
}
}
}
</script>

How to bind a prop value using a function and pass it to another component

Is it possible to bind a prop to a function?
In my example below I’m trying to get a value from a function in the main App.vue and pass it as a prop to the child component customComponent.
e.g. (this example doesn’t work)
App.vue
import customComponent from ‘./custom-component.vue'
<template>
<custom-component
v-bind:myValue="geMyValue()"
></custom-component>
</template>
<script>
export default {
name: "Item",
methods: {
getMyValue: function() {
return 1+3;
}
}
}
</script>
customComponent.vue
<template>
<h3 class="some-custom-layout">custom component</h3>
<input type="button" #click="sendMyValue()" />
</template>
<script>
export default {
name: “custom",
props: ['myValue']
methods: {
sendMyValue: function() {
console.log(this.myValue);
}
}
}
</script>
It's possible, but probably it would be better to use computed properties, if you are going to return value:
<template>
<custom-component
v-bind:myValue="myValue"
></custom-component>
</template>
<script>
export default {
name: "Item",
computed: {
myValue: function() {
return 1+3;
}
}
}
</script>
https://v2.vuejs.org/v2/guide/computed.html