Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use template scope in vue jsx?

Tags:

jsx

vue.js

vuejs2

I define a simple child component(testSlot.vue) like this:

<template>
    <section>
        <div>this is title</div>
        <slot text="hello from child slot"></slot>
    </section>
</template>
<script>
    export default {}
</script>

and we can use it in html template like this

<test-slot>
    <template scope="props">
        <div> {{props.text}}</div>
        <div> this is real body</div>
    </template>
</test-slot>

but how can I use it in jsx ?

like image 317
JsonSong Avatar asked Apr 30 '17 03:04

JsonSong


People also ask

Is Vue template JSX?

Using Vue templates is like using JSX in that they're both created using JavaScript. The main difference is that Vue templates are syntactically valid HTML that can be parsed by spec-compliant browsers and HTML parsers. What does it mean? JSX functions are never used in the actual HTML file, while Vue templates are.

How do you use Vue slots?

How to use it. Using the slot is very easy, we should just write the <slot> component (which is a reserved word in Vue. js) inside the child component's template, where we want to receive data. A child component uses slot.

What is Slot scope in Vuejs?

Render Scope Slot content has access to the data scope of the parent component, because it is defined in the parent. For example: template <span>{{ message }}</span> <FancyButton>{{ message }}</FancyButton> Here both {{ message }} interpolations will render the same content.

What does template tag do in Vue?

Vue uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying component instance's data.


2 Answers

After read the doc three times , I can answer the question myself now O(∩_∩)O .

<test-slot scopedSlots={
    {
        default: function (props) {
            return [<div>{props.text}</div>,<div>this is real body</div>]
        }
    }}>
</test-slot>

the slot name is default.

So. we can access the scope in the scopedSlots.default ( = vm.$scopedSlots.default)

the callback argument 'props' is the holder of props.

and the return value is vNode you cteated with scope which exposed by child component.

I realize the jsx is just a syntactic sugar of render function ,it still use createElement function to create vNode tree.

like image 91
JsonSong Avatar answered Oct 17 '22 08:10

JsonSong


now in babel-plugin-transform-vue-jsx 3.5, you need write in this way:

 <el-table-column
  { ...{
    scopedSlots: {
      default: scope => {
        return (
          <div class='action-list'>

          </div>
        )
      }
    }
  } }>
  </el-table-column>
like image 22
Leon Avatar answered Oct 17 '22 09:10

Leon