天天看点

vue 组件之间函数传递_Vue父子组件之间的参数传递

目录

一 组件之间的参数传递——父传子

1 原理说明

通过子组件的 props 部分,来指明可以接收的参数,父组件通过在标签中写明参数的健值对来传递参数。

props 是表示一个组件的参数部分,props 的写法有两种:

a 通过数组来定义

props:['myprop1','myprop2'...]

b 通过对象来定义

props:{

myName:{

type:String,

required:true,

default:'默认值'

}

}

vue 组件之间函数传递_Vue父子组件之间的参数传递

2 代码

content.vue

商品列表...

{{myTitle}}

export default {

name: "content",

props:['myTitle']

}

App.vue

export default {

name: 'app',

data(){

return {

msg:'hello vue!'

}

}

}

3 效果

vue 组件之间函数传递_Vue父子组件之间的参数传递

二 组件之间的参数传递——子传父

1 原理说明

vue 组件之间函数传递_Vue父子组件之间的参数传递

2 代码

content.vue

商品列表...

{{myTitle}}

点我

export default {

name: "content",

// props:['myTitle']

props: {

myTitle: {

type: String,

required: true,

default: "没传参数"

},

btnfn:{

type: Function

// FCfn(m) {

// this.msg = m

// }

}

}

}

App.vue

export default {

name: 'app',

data() {

return {

msg: '父组件传给子组件!!!'

}

},

methods: {

FCfn(m) {

this.msg = m

}

}

}

3 效果

vue 组件之间函数传递_Vue父子组件之间的参数传递

三 以事件发射的方式实现子传父

1 原理

在子组件中,使用 this.$emit("键","值")

在父组件中,子组件的标签中,使用 @键="msg=$event", 其中$event就能得到值,msg是父组件中 vue 属性。

2 代码

content.vue

商品列表...

{{myTitle}}

点我

export default {

name: "content",

// props:['myTitle']

props: {

myTitle: {

type: String,

required: true,

default: "没传参数"

},

btnfn:{

type: Function

// FCfn(m) {

// this.msg = m

// }

}

},

methods:{

doclick(){

this.$emit('newName','子组件内容')

}

}

}

App.vue

export default {

name: 'app',

data() {

return {

msg: '父组件传给子组件!!!'

}

},

methods: {

FCfn(m) {

this.msg = m

}

}

}

3 效果

vue 组件之间函数传递_Vue父子组件之间的参数传递