Vue中给自定义属性添加属性

  定义组件时,如果是需要参数传递则,将要传递的参数放在`props`中,`props`可以是一个数组也可以是一个字典,字典中可以定义是否是必须传递和参数的类型。如下:
    porps:{
    books:{
        type: Array,
        required: true,
        default: '四大名著'
    }
    }

  

  在传参时,需要在参数前加":"以示是动态数据而非静态数据。如下:
<book-template :books='books'></book-template>

单一根元素:

  如果自定义的组件中,会出现很多html元素,那么根元素必须只能有一个,其余的元素必须包含在这个根元素中。
      错误示例:
<h4>{{title}}</h4>
<div>此标签没有包含在同一根元素下,而是和上面的标签并列</div>
  正确示例:
    <div id="father">
        <h4>{{title}}</h4>
        <div>此标签包含在同一根元素下,都包含在id为father的div下</div>
    </div>

整体的测试代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <title>Vue中给自定义属性添加属性</title>
</head>

<body>
    <div id="app">
        <book-template :books='books'></book-template>
    </div>
    <script>
        Vue.component("book-template", {
            props: ['books'],
            template: `
            <table>
            <thead>
                <tr>
                    <th>序号</th>
                    <th>书名</th>
                    <th>作者</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="book,index in books">
                    <td>{{index+1}}</td>
                    <td>{{book.title}}</td>
                    <td>{{book.author}}</td>
                </tr>
            </tbody>
        </table>
            `
        })
        new Vue({
            el: '#app',
            data: {
                books: [{
                        title: '水浒传',
                        author: '施耐庵',
                    },
                    {
                        title: '三国演义',
                        author: '罗贯中',
                    }
                ]
            }
        })
    </script>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/xshan/p/12336975.html