美文网首页vue偏方
vue通过props方式在子组件中获取相应的对象

vue通过props方式在子组件中获取相应的对象

作者: 赤身荆棘 | 来源:发表于2020-10-09 15:51 被阅读0次

    同人博客搬迁~~~~(播客主页:https://www.cnblogs.com/epines/

    这些方法主要是在这次做项目的过程中发现总结的来的,感觉也挺常用的,所以就简单的记录一下,希望下次不会再犯同样的错误。

    子组件定义props,父组件传入数据,子组件在js中获取的时候使用,如果是在html里面,可以直接把变量渲染上去。

    我就直接从代码上面来进行

    js代码:

    //子组件中,定义传入的变量的类型等  props: {

        data: {

          type: Array,

          require: true    },

        status: {

          type: Boolean,

          require: false    }

      }

    我们可以直接在生命周期函数里面打印props

    mounted(){

      let _this=this;

      console.log(_this._props,9999);         

    }

    方法一:

    所以就可以直接拿取

    mounted() {

        let _this=this;

        let {datas,status}=_this._props;

        console.log(datas,999999);

      },

    方法二:

    有时候会获取不到,这时候可以用一个定时器来获取

      mounted() {

        let _this=this;

        let {datas,status}=_this._props;

        setTimeout(()=>{

          console.log(this._props)

          console.log(datas,111111)

        },2000)

      }

    方法三:

    深拷贝

      mounted() {

        let _this=this;

          let props = {..._this._props};

          console.log(props,"props.......")

      },

    方法四:

    利用watch监听

    //直接监听data,因为这里的props的变量名为data  watch:{

        data(newData,prevData){

          console.log(newData,123654789)

        }

      }

    没错啊,我的data就是一个数组。

    在这四种方法的逐级使用下,终于获取到了我想要的data。

    其实其他几种都是可以的,只是不知道为什么在这次项目中的某个地方,前面几种都失效了,(其他地方是成功的),可能是因为我有毒吧 ╭(╯ε╰)╮。

    相关文章

      网友评论

        本文标题:vue通过props方式在子组件中获取相应的对象

        本文链接:https://www.haomeiwen.com/subject/rnpwixtx.html