Vue父子组件传值
加粗样式父组件向子组件传值:
在组件中,使用选项props来声明从父级组件接收的数据,props的值可以是两种,一种是字符串数组,一种是对象。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>父组件向子组件传值</title>
</head>
<body>
<!-- 父组件显示 -->
<template id="parent1">
<h4>{{message}}</h4>
<!-- 使用v-bind将父组件parent的data(posts)动态传递给props,children组件只能在parent中 -->
<children v-for="post in posts" :id="post.id" :title="post.title"></children>
<!-- 将一个对象的所有属性都作为props传入,与上面一句等价 -->
<children v-for="post in posts" v-bind="post"></children>
</template>
<!-- 子组件显示 -->
<template id="children">
<h4>{{id}} : {{title}}</h4>
</template>
<div id="message-post-demo">
<!-- 静态传递字符串,父组件就是当前的实例 -->
<parent message="来自父组件的消息"></parent>
</div>
</body>
</html>
<script src="vue.global.js" type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript">
const messageApp = Vue.createApp({})
messageApp.component('parent', {
data() {
return {
posts: [{
id: 1,
title: 'My journey with Vue'
},
{
id: 2,
title: 'Blogging with Vue'
},
{
id: 3,
title: 'Why Vue is so fun'
}
]
}
},
props:['message'],//接收父组件messageApp传递的数据
components:{
//创建子组件children
'children':{
props:['id','title'],//接收父组件parent传递的数据
template:'#children'
}
},
template:'#parent1'
})
messageApp.mount('#message-post-demo')
</script>
使用v-model实现子组件向父组件传值,并实现双向绑定。
子——>父时,先给子组件自定义事件并使用$emit(‘事件名’,要传递的数据)方法触发事件,然后父组件使用v-on或@监听子组件的事件。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>子组件向父组件传值</title>
</head>
<template id="custom">
<!-- 为了让子组件正常工作,子组件内的<input>必须将其value属性绑定到一个名为modelValue的props上,在其input事件被触发时,将新的值通过自定义的update:value事件传递 -->
<input :value="modelValue" @input="$emit('update:modelValue',$event.target.value)" />
</template>
<div id="vmode-post-demo">
{{searchText}}<br>
<custom-input v-model="searchText"></custom-input><br>
<!-- 这两个子组件相等 -->
<custom-input :model-value="searchText" @update:model-value="searchText=$event"></custom-input>
</div>
<body>
</body>
</html>
<script src="vue.global.js" type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript">
const blogApp = Vue.createApp({
data() {
return {
searchText: '大帅逼'
}
}
})
blogApp.component('custom-input', {
props: ['modelValue'],
template: '#custom'
})
blogApp.mount('#vmode-post-demo')
</script>