您的位置:首页 > Web前端 > Vue.js

Vue - 父子组件间的参数传递

2021-09-13 14:28 706 查看

TOC

前言

记录下

Vue
中父子组件中的参数传递


父组件向子组件传递参数(props)

  • App.vue
<template>
<Test @sub-event="onTestClick" :url="theme6" />
</template>
<script>
import Test from './components/test.vue'
import theme6 from './assets/home/theme6.jpg'

export default {
name: 'App',
components: {
Test
},
setup () {
return {
theme6
}
}
}
</script>
  • test.vue
<template>
<img :src="url" />
</template>

<script>
export default {
name: 'test',
props: {
url: {
type: String,
default: ''
}
},
setup (props, context) {
console.log(props.url)
}
}
</script>
  • 结果


子组件向父组件传递参数(自定义事件)

  • app.vue
<Test @sub-event="onTestClick" :url="theme6" />

export default {
setup () {
/**
* 自定义事件监听与参数获取
* @param event
*/
function onTestClick (event) {
console.log(event)
}
return {
theme6,
onTestClick
}
}
}

setup自定义事件

test.vue

<template>
<img @click="onImgClick" :src="url" class="size"   />
</template>

<script>

const param = 1

export default {
name: 'test',
props: {
url: {
type: String,
default: ''
}
},
setup (props, context) {
console.log(props.url)
/**
* 写法一: setup自定义事件
* 自定义事件与参数传递
*/
function onImgClick () {
context.emit('sub-event', param)
}
return {
onImgClick
}
}
}
</script>

methods自定义事件

  • test.vue
<template>
<img @click="onImgClick" :src="url" class="size"   />
</template>

<script>
const param = 1
export default {
name: 'test',
props: {
url: {
type: String,
default: ''
}
},
methods: {
/**
* 写法二: methods自定义事件
* 自定义事件与参数传递
*/
onImgClick () {
this.$emit('sub-event', param)
}
}
}
</script>
  • setup
    methods
    中定义本质相同,自定义事件点击结果如下:


- End -
梦想是咸鱼
关注一下吧
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: