Vue 使用篇(二):Vue父子组件间的数据传输

1、问题1

一、问题描述:

咱们一般习惯在组件的mounted阶段对要显示的数据进行必定的处理而后渲染页面。可是子组件在其mounted阶段没法获取父组件的异步数据以及父组件的mounted所建立的数据。vue

二、缘由

  • 父组件的异步数据必须等待其内部执行完毕以后才会被触发,具备必定的滞后;子组件是在父组件建立的同时紧跟着建立的,因此此时去获取父组件的异步数据内部尚未执行完毕,将获取到null。
  • 根据父子组件生命周期执行的顺序,父组件的mounted是在子组件mounted执行完毕后才执行的,所以子组件在其mounted阶段没法获取父组件的mounted所建立的数据。

三、解决方案

为这些数据在子组件中设置watch。当数据更新时将触发操做。bash

四、示例代码

//vue父子组件间的数据传输-问题一:
    父组件mounted中建立的数据或异步数据,子组件mouted中没法得到
// 子组件
Vue.component('child',{
    template:'<h1>child</h1>',
    props:['object','asyncData'],
    mounted () {
        console.log('child mounted object',this.object) // null
        console.log('child mounted asyncData',this.asyncData) // null
    },
    // 解决方案:添加watch
    watch: { 
        object (newOb) {
            console.log('child watch object',nob)
        },
        asyncData (newData) {
            console.log('child watch asyncData',ndata)
        }
    }
})
// 父组件
new Vue({
    el: '#app',
    template: `
        <div id='parent'>
            <child :object='object' :asyncData='asyncData'></child>
        </div>
    `,
    data: {
        object: null,
        asyncData: null
    },
    mounted () {
        setTimeout(() => this.asyncData = 'asyncData',1000)
        this.object = {age :18}
    }
})
复制代码
See the Pen vue父子组件间的数据传输-问题一 by madman0621 ( @madman0621) on CodePen.

2、问题2

一、问题描述:

子组件设置watch监听父组件传输来的数据对象,可是当父组件改变数据对象中的某一个值时,子组件的watch并不会触发。app

二、缘由

子组件设置watch监听父组件传输来的数据对象时,只有当这个数据对象setter时才会触发子组件的watch,即只有给这个数据对象从新赋值才会触发子组件的watch,若是仅仅是修改数据对象中的某个属性,不会触发子组件的watch。异步

三、解决方案

为子组件的watch添加deep:true属性async

四、示例代码

// 子组件设置watch监听父组件传输来的数据对象,
   可是当父组件改变数据对象中的某一个值时,子组件的watch并不会触发。
// 子组件
Vue.component('child',{
    template:'<h1>{{ age }}</h1>',
    props:['object'],
    data () {
        return {
            age : null
        }
    },
    watch: { 
        object: {
            //解决方案
            deep:true,  
            handler (nob) {
                this.age = nob.age
            }
        }
    }
})
// 父组件
new Vue({
    el: '#app',
    template: `
    <div id='parent'>
        <child :object='object'></child>
        <button @click='change'>改变父组件的object</button>
    </div>
  `,
    data: {
        object: null
    },
    mounted () {
        this.object = {age: 18}
    },
    methods: {
        change () {
            this.object.age = 20
        }
    }
})
复制代码
See the Pen vue父子组件间的数据传输-问题二 by madman0621 ( @madman0621) on CodePen.
相关文章
相关标签/搜索