Vue 父子组件传递方式
2018-02-12 17:19
656 查看
问题:
parent.vue <template> <div> 父组件 <child :childObject="asyncObject"></child> </div> </template> <script> import child from './child' export default { data: () => ({ asyncObject: '' }), components: { child }, created () { }, mounted () { // setTimeout模拟异步数据 setTimeout(() => { this.asyncObject = {'items': [1, 2, 3]} console.log('parent finish') }, 2000) } } </script> child.vue <template> <div> 子组件<!--这里很常见的一个问题,就是{{childObject}}可以获取且没有报错,但是{{childObject.items[0]}}不行,往往有个疑问为什么前面获取到值,后面获取不到呢?--> <p>{{childObject.items[0]}}</p> </div> </template> <script> export default { props: ['childObject'], data: () => ({ }), created () { console.log(this.childObject) // 空值 }, methods: { } } </script>通常用v-if 解决 报错问题,以及create 的时候,childObject 值为空的问题
方式一 用 v-if 解决[/b]
parent.vue <template> <div> 父组件 <child :child-object="asyncObject" v-if="flag"></child> </div> </template> <script> import child from './child' export default { data: () => ({ asyncObject: '', flag: false }), components: { child }, created () { }, mounted () { // setTimeout模拟异步数据 setTimeout(() => { this.asyncObject = {'items': [1, 2, 3]} this.flag = true console.log('parent finish') }, 2000) } } </script> child.vue <template> <div> 子组件 <!--不报错--> <p>{{childObject.items[0]}}</p> </div> </template> <script> export default { props: ['childObject'], data: () => ({ }), created () { console.log(this.childObject)// Object {items: [1,2,3]} }, methods: { } } </script>
方式二 用emit,on,bus组合使用[/b]
parent.vue <template> <div> 父组件 <child></child> </div> </template> <script> import child from './child' export default { data: () => ({ }), components: { child }, mounted () { // setTimeout模拟异步数据 setTimeout(() => { // 触发子组件,并且传递数据过去 this.$bus.emit('triggerChild', {'items': [1, 2, 3]}) console.log('parent finish') }, 2000) } } </script> child.vue <template> <div> 子组件 <p>{{test}}</p> </div> </template> <script> export default { props: ['childObject'], data: () => ({ test: '' }), created () { // 绑定 this.$bus.on('triggerChild', (parmas) => { this.test = parmas.items[0] // 1 this.updata() }) }, methods: { updata () { console.log(this.test) // 1 } } } </script>这里使用了bus这个库,parent.vue和child.vue必须公用一个事件总线(也就是要引入同一个js,这个js定义了一个类似let bus = new Vue()的东西供这两个组件连接),才能相互触发 (ps:代码如下,需要安装依赖)
import VueBus from 'vue-bus' Vue.use(VueBus)
来自为知笔记(Wiz)
相关文章推荐
- Vue 父子组件数据传递的四种方式( inheritAttrs + $attrs + $listeners)
- Vue 父子组件传递方式
- vue父子组件数据传递方式
- 前端框架vue.js系列(7):父子组件参数变化传递规范
- Vue2.0的三种常用传值方式、父传子、子传父、非父子组件传值
- vue 父子组件属性传递
- vue-cli中父子组件间的变量传递
- Vue表单类的父子组件数据传递示例
- vue中的$emit 与$on父子组件与兄弟组件的之间通信方式
- vue 父子组件之间的数据传递
- Vue.js 父子组件通信的十种方式
- vue父子组件传递信息
- Vue4种父子组件数据双向传递
- vue父子组件的数据传递
- vue两个组件间值的传递或修改方式
- vue中非父子组件之间传递值
- VUE父子组件之间值传递
- vue向子组件传递参数的两种方式
- vue中父子组件的相互传递
- Vue.js 父子组件相互传递数据