[Vue] Scope slot

Summarize:

Scope slot:
scope is used by the parent component to place the html structure in the child component slot to receive the data of the child component.
Understanding: The data is in the component itself, but the structure generated according to the data needs to be determined by the user of the component. ( Equivalent to child components passing data to parent components) (games data is in the Category component, but the structure traversed by using the data is determined by the App component)

父组件中:
        <Category>
            <template scope="scopeData">
                <!-- 生成的是ul列表 -->
                <ul>
                  <li v-for="g in scopeData.games" :key="g">{
   
   {g}}</li>
                </ul>
            </template>
        </Category>

        <Category>
            <template slot-scope="scopeData">
                <!-- 生成的是h4标题 -->
                <h4 v-for="g in scopeData.games" :key="g">{
   
   {g}}</h4>
            </template>
        </Category>
子组件中:
        <template>
            <div>
                <slot :games="games"></slot>
            </div>
        </template>
		
        <script>
            export default {
                name:'Category',
                props:['title'],
                //数据在子组件自身
                data() {
                    return {
                        games:['红色警戒','穿越火线','劲舞团','超级玛丽']
                    }
                },
            }
        </script>

 Continuing from the previous article, scoped slots can also implement the function of named slots with a name

At this point, our app.vue is the user of Category, and the data is also here

Then we put this data into the category component

But if you write it like this, it will definitely not work, because the data is in the category and cannot be read in app.vue at all. This is a scope problem.

That is, the data is in the category, but according to the structure of the data generation, it needs to be decided by the user of the category, that is, the app needs to get the data in the category.

Solution:

Pass in a value like props in the slot tag,

This writing is to pass the corresponding data (games) to the user of the slot, that is, the subcomponent category passes its games data to its user.

That is, whoever uses this slot will give this data to which user

It is equivalent to app.vue stuffing things into the slot, and the slot sends its corresponding data to app.vue

But the premise is that a template must be wrapped outside, otherwise it will not work

A scope='xxx' is written here , xxx is defined by you, because this xxx is an object that will receive the value you pass , which solves the problem of multiple value passing

So just change it like this

Shorthand: because it supports struct assignment

You can also change scope to slot-scope

Guess you like

Origin blog.csdn.net/qq_37308779/article/details/125827643