1. 父组件向子组件传值
- 子组件在props中创建一个属性,用以接收父组件传过来的值
- 父组件中注册子组件
- 在子组件标签中添加子组件props中创建的属性
- 把需要传给子组件的值赋给该属性
<
div
id
=
"app"
>
<
input
type
=
"text"
v-model
=
"txtRoot"
>
<
child
:
txt
=
"txtRoot"
@
child
=
"childChange"
></
child
>
</
div
>
<
script
src
=
"vue.js"
>
<
/
script
>
<
script
>
const
app
=
new
Vue
({
el:
"#app"
,
data:
{
txtRoot:
"test"
},
components:
{
child:
{
template:
"<p>{{txt}}</p>"
,
props:
[
"txt"
]
}
}
})
<
/
script
>
2. 子组件向父组件传值
- 子组件中需要以某种方式例如input事件的方法来触发一个自定义事件
- 将需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法
- 在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听
<
div
id
=
"app"
>
<
input
type
=
"text"
v-model
=
"txtRoot"
>
<
p
>
{{txtRoot}}
</
p
>
<
child
@
child
=
"childChange"
></
child
>
</
div
>
<
script
src
=
"vue.js"
>
<
/
script
>
<
script
type
=
"text/html"
id
=
"child"
>
<
div
>
<
input
type
=
"text"
v-model
=
"txtChild"
@
input
=
"childEdit"
>
</
div
>
</
script
>
<
script
>
Vue
.
component
(
"child"
, {
data
() {
return
{
txtChild:
"";
}
},
template:
"#child"
,
methods:
{
childEdit
() {
this
.
$emit
(
"child"
,
this
.
txtChild
);
}
}
})
const
app
=
new
Vue
({
el:
"#app"
,
data:
{
txtRoot:
"text"
},
methods:
{
childChange
(
txtChild
) {
this
.
txtRoot
=
txtChild
;
}
}
})
<
/
script
>
3. 父子组件相互传值
例子效果:父组件和子组件中各有一个input标签和一个p标签,通过父组件或子组件中的input进行编辑,同步更改4个标签的显示内容。
<
div
id
=
"app"
>
<
input
type
=
"text"
v-model
=
"txtRoot"
>
<
p
>
{{txtRoot}}
</
p
>
<
child
:
txt
=
"txtRoot"
@
child
=
"childChange"
></
child
>
</
div
>
<
script
src
=
"vue.js"
>
<
/
script
>
<
script
type
=
"text/html"
id
=
"child"
>
<
div
>
<
input
type
=
"text"
v-model
=
"txtChild"
@
input
=
"childEdit"
>
<
p
>
{{txt}}
</
p
>
</
div
>
</
script
>
<
script
>
Vue
.
component
(
"child"
, {
data
() {
return
{
txtChild:
this
.
txt
}
},
template:
"#child"
,
methods:
{
childEdit
() {
this
.
$emit
(
"child"
,
this
.
txtChild
);
}
},
props:
[
"txt"
],
watch:
{
txt
(){
this
.
txtChild
=
this
.
txt
;
}
}
})
const
app
=
new
Vue
({
el:
"#app"
,
data:
{
txtRoot:
"text"
},
methods:
{
childChange
(
txtChild
) {
this
.
txtRoot
=
txtChild
;
}
}
})
<
/
script
>
4. vue的$emit(event,[...args])
参数:
{string} event
[...args]
触发当前实例上的事件。附加参数都会传给监听器回调。
子组件通过$emit触发父组件上绑定的自定义事件,将自身数据作为参数传入事件函数,在父组件的事件函数中将参数赋值给父组件的对应变量。
示例,App.vue中v-on为组件绑定事件(自定义事件),子组件通过$emit触发事件
//header.vue
<
template
>
<
a
class
=
"t-btn"
@
click
=
"showTools"
></
a
>
</
template
>
export default{
methods: {
showTools(){
this.$emit('tools');
}
}
}
//App.vue
<
template
>
<
n-header
@
tools
=
"changePages"
></
n-header
>
</
template
>
export default{
data(){
return{
tools:false,
table:false
}
},
methods:{
changePages(){
if(this.table){
this.table = !this.table;
}else{
this.tools = !this.tools
}
}
}
}