-
父子组件通信
-
data选项为什么是一个函数?
组件是一个聚合体,也是一个整体,他需要一个独立的作用空间
-
为什么data函数需要返回一个返回值,该返回值时对象而不是数组?
-
过程
-
父组件将自己的数据同 v-bind 绑定在 子组件身上
<div id="app"> <Father></Father> </div> <template id="father"> <div> <h3> 这里是father </h3> <Son :money = "money"></Son> </div> </template> <template id="son"> <div> <h3> 这里是son </h3> <p> 我收到了父亲给的 {{ money + 100 }} </p> </div> </template> Vue.component('Father',{ template: '#father', data () { return { money: 3000 } } })
-
子组件通过 props属性接收
Vue.component('Son',{ template: '#son', // props: ['money'] // 数据验证 // props: { // 'money': Number // } props: { 'money': { validator ( val ) { // 验证函数 如果没有通过 验证则会报错,但是并不不会影响程序的继续执行。 return val > 2000 } } } })
-
-
props需要进行数据验证
-
怎么做数据验证
-
验证类型
props: { 'money': Number }
-
验证函数
props: { 'money': { validator ( val ) { // 验证函数 如果没有通过 验证则会报错,但是并不不会影响程序的继续执行。 return val > 2000 } }
-
-
第三方验证
- (TS)
- 插件:vue-validator
-
-
-
子父组件通信
-
数据从子给到父
-
通过自定义事件的触发
-
事件的发布
通过网元素身上绑定事件来发布
-
事件的订阅
通过this.$emit
<div id="app"> <Father></Father> </div> <template id="father"> <div> <h3> 这里是father </h3> <p> 我现在有 {{ gk }} </p> <Son @give = "fn"></Son> </div> </template> <template id="son"> <div> <h3> 这里是son </h3> <button @click = "giveHongbao"> 给父亲红包 </button> </div> </template> </body> <script> Vue.component('Father',{ template: '#father', data ( ) { return { gk: 0 } }, methods: { fn ( val ) { this.gk = val } } }) Vue.component('Son',{ template: '#son', data () { return { money: 5000 } }, methods: { giveHongbao () { this.$emit('give',this.money) } } }) new Vue({ el: '#app' }) </script>
-
-
-
非父子组件通信
-
兄弟元素的加入
在父组件的son中通过ref组件就能够获得所要绑定的组件及属性
“女儿通过”kick () {this.$emit(‘fn’)}来触发father中的fn函数
father的fn函数即可调用son的方法
[外链图片转存失败(img-8DmI8Vfk-1566779335374)(F:\。千锋前端\Vue.js\vue笔记\img\img\非父子组件通信-ref_看图王.png)]
<body> <div id="app"> <Father></Father> </div> </body> <template id="father"> <div> <h3> 这里是父组件 </h3> <Girl @fn = "fn"></Girl> <Son ref = "son"></Son> </div> </template> <template id="son"> <div> <h3> 这里是son组件 </h3> <p v-show = "flag"> o(╥﹏╥)o o(╥﹏╥)o o(╥﹏╥)o o(╥﹏╥)o o(╥﹏╥)o o(╥﹏╥)o </p> </div> </template> <template id="girl"> <div> <h3> 这里是girl组件 </h3> <button @click = "kick"> 揍 </button> </div> </template> <script> Vue.component('Father',{ template: '#father', methods: { fn () { this.$refs.son.changeFlag() } } }) Vue.component('Son',{ template: '#son', data () { return { flag: false } }, methods: { changeFlag () { this.flag = !this.flag } } }) Vue.component('Girl',{ template: '#girl', methods: { kick () { this.$emit('fn') } } }) new Vue({ el: '#app' }) </script>
-
自己的数据自己更改,别人只能间接的去触发自己的方法
-
-
多组件状态共享(vuex)
-
非常规通信方案
-
兵哥建议: 如果标准方案可以实现,就不要用非常规手段
-
- 可以实现子父通信
- 父组件通过 v-bind 绑定一个方法给子组件
- 子组件通过 props选项接收这个方法,然后直接调用
-
- 父组件 通过 v-bind 绑定 一个对象类型数据 给子组件
- 子组件直接使用,如果更改这个数据,那么父组件数据也更改了
- 原因: 同一个地址
- 非常规在哪里?
- 违背了单向数据流
-
vue组件通信
最新推荐文章于 2024-03-22 15:57:07 发布