<base-link> component
I have a Vue component <base-link>, which I use every time I want to have an achor. It's mostly for applying styles specific to links, so that all the links across the whole page look the same without applying global styles.
Make <router-link> use <base-link>
When using <router-link> component to create a link, I cannot apply those styles (<base-link> styles are scoped) unless <router-link> uses my <base-link> component to create the anchor element.
Fortunately <router-link> provides tag attribute, which seems to do exactly that. Unfortunately I can't get it to work. I have 2 problems:
All my components are locally registered (I use ES6 modules with Webpack and import components locally every time I need them). <router-link> doesn't know what <base-link> component is and can't render it. Is there a way to inject a local component for <router-link> to use?
To solve problem #1, I thought it's enough to declare <base-link> component globally. Unfortunately it still doesn't work. This time <base-link> component gets rendered properly, but is still not functional - doesn't react to click events. It seems to me the problem is that it's href attribute isn't set at all. Is there a way to make <router-link> set it properly? (without setting it manually)
Question
How do I solve problems #1 and #2? I suspect #1 might be not possible, but I hope at least #2 is.
Code example
Here is a pen with code below, which illustrates both problems.
const router = new VueRouter({
routes: [
{
path: "/",
component: {
template: '<p>Homepage template</p>'
}
},
{
path: "/subpage",
component: {
template: '<p>Subpage template</p>'
}
}
]
});
// Globally registered BaseLink.
Vue.component('BaseLinkGlobal', {
props: {
href: String
},
template: `
<a
:href="href"
class="BaseLinkGlobal"
>
<slot />
</a>
`
})
const vue = new Vue({
el: "#app",
router,
components: {
// Locally registered BaseLink.
BaseLinkLocal: {
props: {
href: String
},
template: `
<a
:href="href"
class="BaseLinkLocal"
>
<slot />
</a>
`
}
},
template: `
<div>
<!-- 2 router links. One uses locally registered BaseLink
-- and the other one a globally registered one. -->
<nav>
<router-link
to="/"
tag="base-link-local"
>
Home
</router-link>
<router-link
to="/subpage"
tag="base-link-global"
>
Subpage
</router-link>
</nav>
<router-view />
</div>
`
});
You can create a base link component which can double as a normal a tag or <router-link> when you wish.
//Base link
<template>
<component :is="type" :class="{'base': type === 'a'}" v-bind="$attrs">
<slot></slot>
</component>
</template>
<script>
export default {
props: {
routerLink: {
type: Boolean,
default: false
}
},
computed: {
type() {
return this.routerLink ? 'router-link' : 'a'
}
}
}
</script>
<style scopex>
.base {
border: 1px solid red;
}
</style>
Usage
when you want to use it as a normal link just do not provide the router-link prop as below:
<base-link>This is a base a tag</base-link>
To use it as a router-link just add the router-link prop along with the to prop:
<base-link router-link to="/">This is router-link</base-link>
Explanation about the base-link component:
We use a component which is provided by vuejs to render a tag or router-link base on the truthiness of the routerLink prop.
A class of .base is added if it is a normal link i.e a
we bind $attrs which allows us to make the component more transparent i.e allows us to use attributes like href or to without passing them as props.
<base-link href="https://google.com">go to google</base-link>
You can have a look here for more explanation about usage of $attrs
This is for solving problem #2
The global component doesn't inherit the event listener of the router link. You can make it inherit by adding v-on="$listeners" to the global component.
// Globally registered BaseLink.
Vue.component('BaseLinkGlobal', {
props: {
href: String
},
template: `
<a
:href="href"
class="BaseLinkGlobal"
v-on="$listeners"
>
<slot />
</a>
`
})
The link works after adding it: https://codepen.io/jacobgoh101/pen/YvqJxL?editors=0010
Related
Some of our components use other components as property.
A trivial example: <my-interface-component :popup="myPopup"/>
Where myPopup will be a component with a open method that allows to open this external popup component with a message.
In Vue 2 we used to set this property like this:
/**
* #prop {Vue} popup A root popup component to use
*/
popup: {
type: Vue
},
And we could give either a component definition or an existing component reference.
But in Vue 3 there is no more such Vue object. Should I just use Object or is there a more explicit way?
We use the CDN version of Vue 3 with Vanilla JS.
Many thanks
The right type of a component is ComponentOptions|ComponentOptions['setup'] which are simplified for readability as mentioned here:
import {ComponentOptions, PropType } from 'vue'
props:{
popup: {
type: Object as PropType<ComponentOptions|ComponentOptions['setup']>
},
}
However it's recommended to pass components/elements as slots not as props :
Child component :
<template>
<div>
<slot name="popup" />
</div>
</template>
In parent :
<template>
<div>
<template #popup>
<MyPopup />
</template>
</div>
</template>
I have a textarea component that include html tag and I want to get html in edit mode in this component. I use Laravel to generate html.
<template>
<div>
<textarea
:value="content"
:name="name"
:id="id">
<slot></slot>
</textarea>
</div>
</template>
In blade page I used to this component:
<my-component>
<p class="textbox">hello world</p>
</my-component>
when I put this component in page show me tag <slot></slot> in textarea. What should I do? Do you have any solution for my need?
thanks
<textarea> components are treated as static by the Vue renderer, thus after they are put into the DOM, they don't change at all (so that's why if you inspect the DOM you'll see <slot></slot> inside your <textarea>).
But even it if they did change, that wouldn't help much. Just because HTML elements inside <textarea>s don't become their value. You have to set the value property of the TextArea element to make it work.
Anyway, don't despair. It is doable, all you need to overcome the issues above is to bring a small helper component into play.
There are many possible ways to achieve this, two shown below. They differ basically in how you would want your original component's template to be.
Solution: change <textarea> into <textarea-slot> component
Your component's template would now become:
<template>
<div>
<textarea-slot
v-model="myContent"
:name="name"
:id="id">
<slot></slot>
</textarea-slot>
</div>
</template>
As you can see, nothing but replacing <textarea> with <textarea-slot> changed. This is enough to overcome the static treatment Vue gives to <textarea>. The full implementation of <textarea-slot> is in the demo below.
Alternative solution: keep <textarea> but get <slot>'s HTML via <vnode-to-html> component
The solution is to create a helper component (named vnode-to-html below) that would convert your slot's VNodes into HTML strings. You could then set such HTML strings as the value of your <textarea>. Your component's template would now become:
<template>
<div>
<vnode-to-html :vnode="$slots.default" #html="valForMyTextArea = $event" />
<textarea
:value="valForMyTextArea"
:name="name"
:id="id">
</textarea>
</div>
</template>
In both alternatives...
The usage of the my-component stays the same:
<my-component>
<p class="textbox">hello world</p>
</my-component>
Full working demo:
Vue.component('my-component', {
props: ["content", "name", "id"],
template: `
<div>
<textarea-slot
v-model="myContent"
:name="name"
:id="id">
<slot></slot>
</textarea-slot>
<vnode-to-html :vnode="$slots.default" #html="valueForMyTextArea = $event" />
<textarea
:value="valueForMyTextArea"
:name="name"
:id="id">
</textarea>
</div>
`,
data() { return {valueForMyTextArea: '', myContent: null} }
});
Vue.component('textarea-slot', {
props: ["value", "name", "id"],
render: function(createElement) {
return createElement("textarea",
{attrs: {id: this.$props.id, name: this.$props.name}, on: {...this.$listeners, input: (e) => this.$emit('input', e.target.value)}, domProps: {"value": this.$props.value}},
[createElement("template", {ref: "slotHtmlRef"}, this.$slots.default)]
);
},
data() { return {defaultSlotHtml: null} },
mounted() {
this.$emit('input', [...this.$refs.slotHtmlRef.childNodes].map(n => n.outerHTML).join('\n'))
}
});
Vue.component('vnode-to-html', {
props: ['vnode'],
render(createElement) {
return createElement("template", [this.vnode]);
},
mounted() {
this.$emit('html', [...this.$el.childNodes].map(n => n.outerHTML).join('\n'));
}
});
new Vue({
el: '#app'
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<my-component>
<p class="textbox">hell
o world1</p>
<p class="textbox">hello world2</p>
</my-component>
</div>
Breakdown:
Vue parses the <slot>s into VNodes and makes them available in the this.$slots.SLOTNAME property. The default slot, naturally, goes in this.$slots.default.
So, in runtime, you have available to you what has been passed via <slot> (as VNodes in this.$slots.default). The challenge now becomes how to convert those VNodes to HTML String? This is a complicated, still open, issue, which may get a different solution in the future, but, even if it ever does, it will most likely take a while.
Both solutions above (template-slot and vnode-to-html) use Vue's render function to render the VNodes to the DOM, then picks up the rendered HTML.
Since the supplied slots may have arbitrary HTML, we render the VNodes into an HTML Template Element, which doesn't execute any <script> tags.
The difference between the two solutions is just how they "handle back" the HTML generated from the render function.
The vnode-to-html returns as an event that should be picked up by the parent (my-component) which uses the passed value to set a data property that will be set as :value of the textarea.
The textarea-slot declares itself a <textarea>, to the parent doesn't have to. It is a cleaner solution, but requires more care because you have to specify which properties you want to pass down to the <textarea> created inside textarea-slot.
Wrapping up and off-the-shelf alternatives
However possible, it is important to know that Vue, when parsing the declared <template> into <slot>s, will strip some formatting information, like whitespaces between top-level components. Similarly, it strips <script> tags (because they are unsafe). These are caveats inherent to any solutions using <slot>s (presented here or not). So be aware.
Typical rich text editors for Vue, work around this problem altogether by using v-model (or value) attributes to pass the code into the components.
Well known examples include:
vue-ace-editor: Demo/codepen here.
Vue Prism Editor: Demo here.
vue-monaco (the code editor that powers VS Code): demo here.
vue-codemirror: Demo here. This is by far the most starred on github.
They all have very good documentation in their websites (linked above), so it would be of little use for me to repeat them here, but just as an example, see how codemirror uses the value prop to pass the code:
<codemirror ref="myCm"
:value="code"
:options="cmOptions"
#ready="onCmReady"
#focus="onCmFocus"
#input="onCmCodeChange">
</codemirror>
So that's how they do it. Of course, if <slot>s - with its caveats - fit your use case, they can be used as well.
The short answer is NOT POSSIBLE
Your slot is put inside an textarea tag. Textare tag is only able to display the text content on its box.
So in the case you want a kind of "HTML edit mode", you may looking for an WYSIWYG editor, I recommend you can use CKEditor for VueJS, the editor even will allow you to direct edit HTML code
https://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/frameworks/vuejs.html
Your HTML
<div id="app">
<ckeditor :editor="editor" v-model="editorData" :config="editorConfig"></ckeditor>
</div>
Your Component
const app = new Vue( {
el: '#app',
data: {
editor: ClassicEditor,
editorData: '<p>Editable Content HTML</p>',
editorConfig: {
// The configuration of the editor.
}
}
} );
In your case if you want to write your own content editor you can use div with attribute contenteditable="true" rather than textarea. After this you can write your text decoration methods ...
The generated html with laravel store in myhtml and use it in vue component.
Example: I also uploaded to codesandbox [Simple Vue Editor]
<template>
<div>
<button #click="getEditorCotent">Get Content</button>
<button #click="setBold">Bold</button>
<button #click="setItalic">Italic</button>
<button #click="setUnderline">Underline</button>
<button #click="setContent">Clear</button>
<div class="myeditor" ref="myeditor" contenteditable v-html="myhtml" #input="onInput"></div>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String
},
data: () => {
return {
myhtml:
"<h1>Simple editor</h1><p style='color:red'>in vue</p><p>Hello world</p>" // from laravel server via axios call
};
},
methods: {
onInput(e) {
// handle user input
// e.target.innerHTML
},
getEditorCotent() {
console.log(this.$refs.myeditor.innerHTML);
},
setBold() {
document.execCommand("bold");
},
setItalic() {
document.execCommand("italic");
},
setUnderline() {
document.execCommand("underline");
},
setContent() {
// that way set your html content
this.myhtml = "<b>You cleared the editor content</b>";
}
// PS. Good luck!
}
};
</script>
<style scoped>
.myeditor {
/* text-align: left; */
border: 2px solid gray;
padding: 5px;
margin: 20px;
width: 100%;
min-height: 50px;
}
</style>
I am working on account removal on a Chrome extension and I have the following button:
<button #click="remove" id="button_remove" class="btn btn-default" style="float: right;">Remove Account</button>
JS
methods:{
remove(event){
app.removeAccountData(url,apikey);
}
},
I also have this router-link:
<router-link :to="{ name: 'RemovedWId', params: { accountid: chosenAccount.apikey}}" text="delete_account"><span class="glyphicon glyphicon-trash" aria-hidden="true" style="margin-top: 2px; cursor: pointer;"></span> Remove Account</router-link>
Is there a way to use the router-link with the JS function?
Vue 2
With Vue Router 3, <router-link> is a component wrapper around <a>, so we'll need to use the .native modifier for it to properly receive the event:
<router-link #click.native="removeAccount" to="/remove">Remove</router-link>
demo 1
Vue 3
With Vue Router 4, <router-link> no longer passes its attributes and event handlers to its inner component, and Vue 3 no longer supports the .native event modifier. You'd have to apply the #click handler manually via <router-link>'s custom default slot.
Apply <router-link>'s custom prop to enable the default slot customization.
In the <router-link>'s default slot, add an <a> and bind the following slot props:
a. href (the resolved URL to the route) to <a>.href
b. navigate (the method that performs the navigation to the route) to <a>.#click. Pass navigate and the $event (a special argument) to a method that runs the secondary method and then the navigate() method with $event as the argument.
<router-link to="/remove" custom v-slot="{ href, navigate }">
<a :href="href" #click="wrapNavigate(navigate, $event)">Remove</a>
</router-link>
export default {
methods: {
removeAccount() {
// ...
},
wrapNavigate(navigate, event) {
this.removeAccount()
navigate(event)
},
},
}
demo 2
I am currently trying to get this thing working with Vue Router.
The goal is:
If Nav#1 is clicked, a Component which includes another Router-Link with SubNav#1 preselected should appear.
I could get it to work in the way that if you click Nav#1, the Component with SubNav#1 with an already active class appeared. The problem is that the active class from Nav#1 is removed and it is not possible to navigate to Nav#2 or N#3. If I click on the Router-Link from Nav#2 or #3 nothing happens...
routes.js:
{ path: '/app', component: App,
children: [
{ path: 'Nav#1', component: Nav#1_Content,
children: [
{ path: 'SubNav#1', component: SubNav#1_Content},
{ path: 'SubNav#2', component: SubNav#2_Content}
]},
{ path: 'Nav#2', component: Nav#2_Content},
{ path: 'Nav#3', component: Nav#3_Content},
]}
+ custom linkActiveClass in new VueRouter instance.
Nav component:
<router-link to="Nav#1/SubNav#1">Nav #1</router-link>
<router-link to="Nav#2">Nav #2</router-link>
<router-link to="Nav#3">Nav #3</router-link>
Nav#1_Content component:
<template>
<div>
<nav>
<router-link to="SubNav#1" tag="div">SubNav#1</router-link>
<router-link to="SubNav#2" tag="div">SubNav#2</router-link>
</nav>
<router-view></router-view>
</div>
</template>
When you specify a value for the to prop on a <router-link> tag, you are specifying the exact path of the route to go to.
Since all of your example paths are under the /app root path, I'm not sure how you are getting any of these links to work.
That said, you need to get rid of the # signs in your route path definitions. When providing a path to Vue Router, it strips anything after the # sign and saves it as the $route.hash value.
So, use the full pathname in the to prop for your <router-link> tags and drop the # signs.
Here's a working fiddle.
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
}