I want create component with textarea and pass data inside that like
<c-textarea> hello world </c-textarea>
but the classic <slot/> tag not work inside of textarea
what's simplest and cleanest alternative
<template>
<textarea><slot/></textarea>
</template>
in Vue.js 3
You should use value & input to bind the content instead of using slot
Here is the updated version of CTextarea component
<template>
<textarea :value="modelValue" #input="$emit('update:modelValue', $event.target.value)">
</textarea>
</template>
<script>
export default {
name: 'CTextarea',
emits: ['update:modelValue'],
props: {
modelValue: String,
},
};
</script>
check this woking demo
You can extract the content of a slot:
<template>
<textarea>{{ $slots.default ? $slots.default()[0].children : ''}}</textarea>
</template>
Basically, this builds the slot manually, which gives you a VNode element, where children contains the slot content.
I would really try to find another way though, this is coarse, error prone and most likely not what you want to do.
Personally, I would stick to the v-model approach.
I'll try to explain my problem.
I have a VueJS component, that uses slots in its template. For example:
App.vue:
<template>
<div>
<slot name="content" :content="somecontent"></slot>
</div>
</template>
<script>
export default {
data(){
return {
somecontent: "test"
}
}
}
</script>
And now I would like to initialize it like this:
<App>
<template #content="somecontent">
<div>{{somecontent}}</div>
</template>
</App>
The idea is that the user would be able to override a part of the widget content and still have some data that the widget provides. A real-life example would be a list where the elements are being loaded remotely and the user can override the list item template.
I know now that custom elements do not support scoped slots. Is there any other way to achieve this? The template syntax does not need to be like above.
Thanks for any info that could solve my problem.
Can I not do something like this?
<template v-if="options.columns">
one thing...
</template>
<template v-else slot-scope="scope">
something else. scope doesn't work here. :(
</template>
When I try to do this, scope becomes undefined. The moment I remove v-if, else and use scope it works as expected.
I was facing with the exact same problem, what's worse, mine is failing silently - I didn't see any errors.
Solution #1 move if else condition to the inner scope of <template>
As David Japan pointed out, you can check if else condition in the inner scope of slot-scope:
<template slot-scope="scope">
<span v-if="options.columns">one thing...</span>
<span v-else>something else.</span>
</template>
Solution #2 use v-slot instead of slot-scope
<template v-slot="scope" v-if="options.columns">
one thing...
</template>
<template v-slot="scope" v-else>
something else.
</template>
However I don't know why v-slot fixes it, I searched both in the official documentation and online but no clues.
The solution is a workaround:
Create 2 different SFC for each possible use case and do conditional rendering.
Vuetify example:
// App.vue
<div>
<ListMD v-if="this.$vuetify.breakpoint.name === 'md'" />
<ListXS v-if="this.$vuetify.breakpoint.name === 'xs'" />
</div>
In Vue.js component you cannot have more than one template tag.
Why not using 'is' property for dynamic component ?
<template>
<div :is='my-component'></div>
</template>
So you can load a component dynamicaly.
https://v2.vuejs.org/v2/guide/components.html#Dynamic-Components
I'm writing reusable components for our internal framework that abstract away some monkey code. Most of the scenario's are implemented with slots and work great. However, some scenario's require rendering templates inside for loops, and unfortunately slots aren't supported there.
I came up with the following (working) code:
<template>
<div class="form-group">
<label for.bind="titleSafe" class="control-label">{title}</label>
<select id.bind="titleSafe" value.bind="value" class="form-control">
<option repeat.for="item of itemsSource" >
<template replaceable part="item-template" containerless>${item}</template>
</option>
</select>
</div>
</template>
This code has, IMO, multiple issues that make it a bad candidate for including it in a framework:
It doesn't support default templates like slots does, so when you have only 1 replacable part the syntax is needlessly verbose
Having to use 2 different templating systems (slots + replace-part) in my project seems really counter intuitive and will certainly create confusion/bugs in my dev team
When you use template parts in the example I provided above, you need to know I declared 'item' as iterator in my for loop in order to construct your template correctly
Therefore I went looking for alternatives. After some research I came up with something like this:
<template>
<div class="form-group">
<label for.bind="titleSafe" class="control-label">{title}</label>
<select id.bind="titleSafe" value.bind="value" class="form-control">
<option repeat.for="item of itemsSource" >
<!-- I want to insert my custom element here -->
</option>
</select>
</div>
<slot></slot>
</template>
The above is my select-item custom element. Then I would also create another custom element for the templating of the repeatable item, like select-item-template, I would then use the two together like this:
<select-item title="myTitle" items-source="myItems">
<select-item-template><span>${myItemsProperty}</span></select-item-template>
</select-item>
The strength of this approach would be that you can create complex 'root' custom elements with one default slot. In this slot, you could then define multiple custom 'child' elements that the root element can search for when it's initialized (I know you can do this with the #child and #children decorators, so that part is covered). I'm a bit lost on how I would have to use these custom child element's content in my root custom element though.. How would I take my span element in the above example and prepare it's content to be rendered in the repeater? And would it be possible to take the repeated item set it as the template's datasource so I don't have to specify itemin my templates?
I hope I didn't make this too verbose, but I wanted to explain what my functional requirement is. If you have any resource that can point me in the right direction I would be very grateful!
Use the processContent attribute to transform the element content into a part replacement. The component will still use replace-part internally but consumers of the component won't be exposed to this implementation detail.
https://gist.run?id=2686e551dc3b93c494fa9cc8a2aace09
picker.html
<template>
<label repeat.for="item of itemsSource" style="display: block">
<input type="radio" value.bind="item" checked.bind="value">
<template replaceable part="item-template">${item}</template>
</label>
</template>
picker.js
import {bindable, processContent} from 'aurelia-templating';
import {bindingMode} from 'aurelia-binding';
import {FEATURE} from 'aurelia-pal';
#processContent(makePartReplacementFromContent)
export class Picker {
#bindable itemsSource = null;
#bindable({ defaultBindingMode: bindingMode.twoWay }) value = null;
}
function makePartReplacementFromContent(viewCompiler, viewResources, element, behaviorInstruction) {
const content = element.firstElementChild;
if (content) {
// create the <template>
const template = document.createElement('template');
// support browsers that do not have a real <template> element implementation (IE)
FEATURE.ensureHTMLTemplateElement(template);
// indicate the part this <template> replaces.
template.setAttribute('replace-part', 'item-template');
// replace the element's content with the <template>
element.insertBefore(template, content);
element.removeChild(content);
template.content.appendChild(content);
return true;
}
}
usage
<template>
<require from="picker"></require>
<h1>Default Item Template</h1>
<picker items-source.bind="colors" value.bind="color"></picker>
<h1>Custom Item Template</h1>
<picker items-source.bind="colors" value.bind="color">
<em css="color: ${item}">
${item}
</em>
</picker>
</template>
I'm trying to use the on click directive inside a component but it does not seem to work. When I click the component nothings happens when I should get a 'test clicked' in the console. I don't see any errors in the console, so I don't know what am I doing wrong.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vuetest</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
App.vue
<template>
<div id="app">
<test v-on:click="testFunction"></test>
</div>
</template>
<script>
import Test from './components/Test'
export default {
name: 'app',
methods: {
testFunction: function (event) {
console.log('test clicked')
}
},
components: {
Test
}
}
</script>
Test.vue (the component)
<template>
<div>
click here
</div>
</template>
<script>
export default {
name: 'test',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
If you want to listen to a native event on the root element of a component, you have to use the .native modifier for v-on, like following:
<template>
<div id="app">
<test v-on:click.native="testFunction"></test>
</div>
</template>
or in shorthand, as suggested in comment, you can as well do:
<template>
<div id="app">
<test #click.native="testFunction"></test>
</div>
</template>
Reference to read more about native event
I think the $emit function works better for what I think you're asking for. It keeps your component separated from the Vue instance so that it is reusable in many contexts.
// Child component
<template>
<div id="app">
<test #click="$emit('test-click')"></test>
</div>
</template>
Use it in HTML
// Parent component
<test #test-click="testFunction">
It's the #Neps' answer but with details.
Note: #Saurabh's answer is more suitable if you don't want to modify your component or don't have access to it.
Why can't #click just work?
Components are complicated. One component can be a small fancy button wrapper, and another one can be an entire table with bunch of logic inside. Vue doesn't know what exactly you expect when bind v-model or use v-on so all of that should be processed by component's creator.
How to handle click event
According to Vue docs, $emit passes events to parent. Example from docs:
Main file
<blog-post
#enlarge-text="onEnlargeText"
/>
Component
<button #click="$emit('enlarge-text')">
Enlarge text
</button>
(# is the v-on shorthand)
Component handles native click event and emits parent's #enlarge-text="..."
enlarge-text can be replaced with click to make it look like we're handling a native click event:
<blog-post
#click="onEnlargeText"
></blog-post>
<button #click="$emit('click')">
Enlarge text
</button>
But that's not all. $emit allows to pass a specific value with an event. In the case of native click, the value is MouseEvent (JS event that has nothing to do with Vue).
Vue stores that event in a $event variable. So, it'd the best to emit $event with an event to create the impression of native event usage:
<button v-on:click="$emit('click', $event)">
Enlarge text
</button>
As mentioned by Chris Fritz (Vue.js Core Team Emeriti) in VueCONF US 2019
If we had Kia enter .native and then the root element of the base input changed from an input to a label suddenly this component is broken and it's not obvious and in fact, you might not even catch it right away unless you have a really good test. Instead by avoiding the use of the .native modifier which I currently consider an anti-pattern, and will be removed in Vue 3, you'll be able to explicitly define that the parent might care about which element listeners are added to...
With Vue 2
Using $listeners:
So, if you are using Vue 2, a better option to resolve this issue would be to use a fully transparent wrapper logic. For this, Vue provides a $listeners property containing an object of listeners being used on the component. For example:
{
focus: function (event) { /* ... */ }
input: function (value) { /* ... */ },
}
and then we just need to add v-on="$listeners" to the test component like:
Test.vue (child component)
<template>
<div v-on="$listeners">
click here
</div>
</template>
Now the <test> component is a fully transparent wrapper, meaning it can be used exactly like a normal <div> element: all the listeners will work, without the .native modifier.
Demo:
Vue.component('test', {
template: `
<div class="child" v-on="$listeners">
Click here
</div>`
})
new Vue({
el: "#myApp",
data: {},
methods: {
testFunction: function(event) {
console.log('test clicked')
}
}
})
div.child{border:5px dotted orange; padding:20px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="myApp">
<test #click="testFunction"></test>
</div>
Using $emit method:
We can also use the $emit method for this purpose, which helps us to listen to a child component's events in the parent component. For this, we first need to emit a custom event from a child component, like:
Test.vue (child component)
<test #click="$emit('my-event')"></test>
Important: Always use kebab-case for event names. For more information and a demo regading this point please check out this answer: VueJS passing computed value from component to parent.
Now, we just need to listen to this emitted custom event in the parent component, like:
App.vue
<test #my-event="testFunction"></test>
So basically, instead of v-on:click or the shorthand #click we will simply use v-on:my-event or just #my-event.
Demo:
Vue.component('test', {
template: `
<div class="child" #click="$emit('my-event')">
Click here
</div>`
})
new Vue({
el: "#myApp",
data: {},
methods: {
testFunction: function(event) {
console.log('test clicked')
}
}
})
div.child{border:5px dotted orange; padding:20px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="myApp">
<test #my-event="testFunction"></test>
</div>
With Vue 3
Using v-bind="$attrs":
Vue 3 is going to make our life much easier in many ways. One example is that it will help us create a simpler transparent wrapper with less config, by just using v-bind="$attrs". By using this on child components, not only will our listener work directly from the parent, but also any other attributes will also work just like they would with a normal <div>.
So, with respect to this question, we will not need to update anything in Vue 3 and your code will still work fine, as <div> is the root element here and it will automatically listen to all child events.
Demo #1:
const { createApp } = Vue;
const Test = {
template: `
<div class="child">
Click here
</div>`
};
const App = {
components: { Test },
setup() {
const testFunction = event => {
console.log("test clicked");
};
return { testFunction };
}
};
createApp(App).mount("#myApp");
div.child{border:5px dotted orange; padding:20px;}
<script src="//unpkg.com/vue#next"></script>
<div id="myApp">
<test v-on:click="testFunction"></test>
</div>
But, for complex components with nested elements where we need to apply attributes and events to the <input /> instead of the parent label we can simply use v-bind="$attrs"
Demo #2:
const { createApp } = Vue;
const BaseInput = {
props: ['label', 'value'],
template: `
<label>
{{ label }}
<input v-bind="$attrs">
</label>`
};
const App = {
components: { BaseInput },
setup() {
const search = event => {
console.clear();
console.log("Searching...", event.target.value);
};
return { search };
}
};
createApp(App).mount("#myApp");
input{padding:8px;}
<script src="//unpkg.com/vue#next"></script>
<div id="myApp">
<base-input
label="Search: "
placeholder="Search"
#keyup="search">
</base-input><br/>
</div>
A bit verbose but this is how I do it:
#click="$emit('click', $event)"
UPDATE: Example added by #sparkyspider
<div-container #click="doSomething"></div-container>
In div-container component...
<template>
<div #click="$emit('click', $event);">The inner div</div>
</template>
Native events of components aren't directly accessible from parent elements. Instead you should try v-on:click.native="testFunction", or you can emit an event from Test component as well. Like v-on:click="$emit('click')".
One use case of using #click.native is when you create a custom component and you want to listen to click event on the custom component. For example:
#CustomComponent.vue
<div>
<span>This is a custom component</span>
</div>
#App.vue
<custom-component #click.native="onClick"></custom-component>
#click.native always work for this situation.
App.vue
<div id="app">
<test #itemClicked="testFunction($event)"/>
</div>
Test.vue
<div #click="$emit('itemClicked', data)">
click here
</div>
From the documentation:
Due to limitations in JavaScript, Vue cannot detect the following changes to an array:
When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
When you modify the length of the array, e.g. vm.items.length = newLength
In my case i stumbled on this problem when migrating from Angular to VUE. Fix was quite easy, but really difficult to find:
setValue(index) {
Vue.set(this.arr, index, !this.arr[index]);
this.$forceUpdate(); // Needed to force view rerendering
}