1.子组件通过事件和父组件进行通信
由于Vue中单向数据流的概念,父组件传递给子组件的值,子组件只能展示不能修改,所以需要使用事件与父组件通信修改父组件中的值
const app = Vue.createApp({
data(){
return {count:2}
},
methods:{
hanldeAddOne(){
this.count +=1;
}
},
// 在子组件中派发的事件可以在父组件中监听
template:'<div><counter :count="count" @add-one="hanldeAddOne"/></div>'
})
app.component('counter',{
props:['count'],
methdos:{
handleClick(){
// 派发addOne事件
this.$emit('addOne')
}
},
template:
`
<div @click="handleClick">{{count}}</div>
`
})
2.子组件触发函数时携带参数
const app = Vue.createApp({
data(){
return {count:2}
},
methods:{
// 子组件中传来的参数可以在这里接收到
hanldeAdd(param1,param2){
this.count += param1 ;
}
},
// 在子组件中派发的事件可以在父组件中监听
template:'<div><counter :count="count" @add="hanldeAdd"/></div>'
})
app.component('counter',{
props:['count'],
methdos:{
handleClick(){
// 派发add事件
this.$emit('add',2,3)
}
},
template:
`
<div @click="handleClick">{{count}}</div>
`
})
3.子组件中可以派发的事件进行声明和检测
const app = Vue.createApp({
data(){
return {count:2}
},
methods:{
// 子组件中传来的参数可以在这里接收到
hanldeAdd(param1,param2){
this.count += param1 ;
}
},
// 在子组件中派发的事件可以在父组件中监听
template:'<div><counter :count="count" @add="hanldeAdd"/></div>'
})
app.component('counter',{
props:['count'],
emits:['add'],
methdos:{
handleClick(){
// 派发add事件
this.$emit('add',2,3)
}
},
template:
`
<div @click="handleClick">{{count}}</div>
`
})
const app = Vue.createApp({
data(){
return {count:2}
},
methods:{
// 子组件中传来的参数可以在这里接收到
hanldeAdd(param1){
this.count += param1 ;
}
},
// 在子组件中派发的事件可以在父组件中监听
template:'<div><counter :count="count" @add="hanldeAdd"/></div>'
})
app.component('counter',{
props:['count'],
//对传递的参数进行检测
emits:funtion(param1){
if(param1<10){return true}else return false;
},
methdos:{
handleClick(){
// 派发add事件
this.$emit('add',2)
}
},
template:
`
<div @click="handleClick">{{count}}</div>
`
})
3.通过v-model改造上面的代码
const app = Vue.createApp({
data(){
return {count:2}
},
template:'<div><counter v-model="count"/></div>'
})
app.component('counter',{
props:['modelValue'],
emits:['add'],
methdos:{
handleClick(){
// add
this.$emit('update:modelValue',2)
}
},
template:
`
<div @click="handleClick">{{modelValue}}</div>
`
})
// 或者可以将modelValue改为其他的名字
const app = Vue.createApp({
data(){
return {count:2}
},
template:'<div><counter v-model:app="count"/></div>'
})
app.component('counter',{
props:['app'],
emits:['add'],
methdos:{
handleClick(){
// add
this.$emit('update:app',2)
}
},
template:
`
<div @click="handleClick">{{app}}</div>
`
})