码迷,mamicode.com
首页 > 其他好文 > 详细

父组件和子组件相互传值

时间:2019-07-15 12:05:13      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:this   http   https   判断   dash   相互   mount   脚本   title   

父组件向子组件传值 props

父组件:

 标签

<child type="note" :defaultValue="mdl.title"></child>

  

子组件:

 标签 

<p>{{type}}</p>

 脚本

props: {
    type: null,
    defaultValue : null
},

   或者

props: [‘type‘, ‘defaultValue‘],

我一般默认设null(不初始值会报错),然后在beforeMount()方法做判断和赋值

beforeMount () {
    if (this.defaultValue) {
      this.setData(this.defaultValue)
    }
},
methods: {
    setData (data) {
      this.fileList = data
    },
}

注:如果父组件传进来的带下划线,传进来的数据是a-bc, vue转化成aBc, 在js 里面写aBc

 

子组件更新值给父组件 this.$emit

父组件:

 标签

<child v-on:change="showChildChange"></child>

  或者

<child @change="showChildChange"></child>

 脚本  

methods: {
    showChildChange (value) {
        console.log(‘value‘, value)
    }
}

  

子组件:

this.$emit 子组件发射自定义事件sendiptVal 并携带要传递给父组件的值

脚本

methods: {
    handleChange ({ data }) {
      this.$emit(‘change‘, data)
    },
},

如果要传递给父组件很多值,这些值要作为参数依次列出 如 this.$emit(‘change‘, 1, 2); 

 

还有一种watch(监听)父组件数据的方法,可参考:https://www.jianshu.com/p/1b7e8a28d836

 

参考:

vue 中父子组件传值:props和$emit:https://www.cnblogs.com/rlann/p/7163045.html

vue—子组件修改父组件的值:https://blog.csdn.net/sinat_36422236/article/details/79403718

 

父组件和子组件相互传值

标签:this   http   https   判断   dash   相互   mount   脚本   title   

原文地址:https://www.cnblogs.com/cxscode/p/11187989.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!