ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] >[success] # 组件间传值及传值校验 在本节将讲述 **组件之间的传值的方式** ,以及传过来的 **值得校验** 。 >[success] ## 组件间传值 1. **父传子** **父组件** 中调用 **子组件标签** ,通过在标签上添加 **属性** 的形式 **给子组件传值** ,子组件通过 **props** 来接收 **父组件** 传入的值 **index.html** ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> 组件间传值及传值校验</title> <!-- 通过cdn方式引入vue --> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="root"></div> </body> <script> const app = Vue.createApp({ template: ` <div> <test content="hello world" /> </div>` }) // 创建全局组件 app.component('test', { props: ['content'], // 接收父组件传入的值 template: '<div>{{content}}</div>' }) const vm = app.mount('#root') </script> </html> ~~~ >[success] ## 传值校验 有时候 **子组件 props 接收父组件传入值** 不是想要的 **类型** ,所以在这里讲一下 **子组件如何校验父组件传过来的值** 。 **index.html** ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> 组件间传值及传值校验</title> <!-- 通过cdn方式引入vue --> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="root"></div> </body> <script> const app = Vue.createApp({ data(){ return { num: 10000 } }, template: ` <div> <test :content="num" /> </div>` }) // 创建全局组件 // type: String, Boolean, Array, Object, Function, Symbol 数据的类型 // required: true / false 必填 // default: 默认值 // validator函数:可以做一些逻辑性的校验,例如:传入的值是否小于1000,返回布尔值结果 app.component('test', { props: { content: { type: Number, // 类型:校验要传入的类型格式Number类型 default: 789, // 默认值:数组、对象时需要是一个函数返回{}或[] validator: function(value) { // value:父组件传递过来的值 return value < 1000 } } }, template: '<div>{{content}}</div>' }) const vm = app.mount('#root') </script> </html> ~~~