Create text node with custom render function in Vue.js

后端 未结 5 1506
栀梦
栀梦 2021-02-13 02:26

I\'m using a my-link component to wrap an anchor tag on demand around various items. For that purpose a custom render method is used - however the

5条回答
  •  深忆病人
    2021-02-13 03:16

    You can actually get around having to use the _v method mentioned in answers above (and potentially avoid using an internal Vue method that might get renamed later) by changing your implementation of the the MyLink component to be a functional component. Functional components do not require a root element, so it would get around having to put a span around the non-link element.

    MyLink could be defined as follows:

    const MyLink = {
      functional: true,
      name: 'my-link',
      props: { url: String },
      render(createElement, context) {
        let { url } = context.props
        let slots = context.slots()
        if (url) {
          return createElement(
              'a', {
                attrs: { href: url }
              }, slots.default
          );
        }
        else {
          return slots.default 
        }
      }
    };
    

    Then to use it, you could do something like this in a different component:

    {{ item.text }}

    See: https://codepen.io/hunterae/pen/MZrVEK?editors=1010

    Also, as a side-note, it appears your original code snippets are naming the file as Link.vue. Since you are defining your own render function instead of using Vue's templating system, you could theoretically rename the file to Link.js and remove the beginning and closing script tags and just have a completely JS component file. However, if you component includes custom systems (which your snippet did not), this approach will not work. Hope this helps.

提交回复
热议问题