前言
记录下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
中定义本质相同,自定义事件点击结果如下: