Vue.js 父子组件通信

父子组件通信

理解:
data选项为什么是一个函数?
组件是一个聚合体,也是一个整体,它需要一个独立的作用空间,也就是它的数据需要是独立的,目前js的最大特点是函数式编程,而函数恰好提供了一个独立作用域,所以我们data在出根组件外都是函数
理解: 为什么data函数需要返回一个返回值,返回值还是对象,不能是数组吗?
Vue通过es5的Object.definePerproty属性对一个对象进行getter和setter设置,而data选项是作为Vue深入响应式核心的选项
过程

父组件将自己的数据同 v-bind 绑定在 子组件身上
子组件通过 props属性接收

<template id="father">
    <div>
        <h3> 这里是father </h3>
        <Son :money = "money"></Son>
    </div>
</template>

<template id="son">
    <div>
        <h3> 这里是son </h3>
        <p> 我收到了父亲给的  </p>
    </div>
</template>

<script>
  Vue.component('Father',{
    template: '#father',
    data () {
      return {
        money: 10000
      }
    }
  })

  Vue.component('Son',{
    template: '#son',
    props: ['money']
  })

  new Vue({
    el: '#app'
  })
</script>

props属性数据验证
验证数据类型
验证数据大小【 判断条件 】

// props: ['money']
// 数据验证
// props: {
//   'money': Number 
// }
props: {
    'money': {
        validator ( val ) { // 验证函数
            return val > 2000
        }
    }
}

工作中: 第三方验证
TypeScript [ TS ]
插件 vue-validator 等

猜你喜欢

转载自blog.csdn.net/weixin_45663264/article/details/102557647