上海城乡建设网站首页,简单又快的科学小制作,网站建站专业,福州网站建设哪家公司好vue中的this.$emit方法 使用一#xff1a;$emit使用二#xff1a;$emit update 和 .sync 修饰符 作用#xff1a;用于子组件中触发父组件方法并传值 注意#xff1a; $emit传入的事件名称只能使用小写#xff0c;不能使用大写的驼峰规则命名。 使用一#xff1a;$emit …vue中的this.$emit方法 使用一$emit使用二$emit update 和 .sync 修饰符 作用用于子组件中触发父组件方法并传值 注意 $emit传入的事件名称只能使用小写不能使用大写的驼峰规则命名。 使用一$emit
//子组件中
templatebutton clickhandleChildEvent子组件中触发的事件/button
/templatescript
export default {name:ChildComponent,methods: {handleChildEvent() {// 触发自定义事件并传递数据给父组件this.$emit(parent-event, Hello, World!);}}
}
/script //父组件中
child-component parent-eventhandleParentEvent/script
export default {name: ParentComponent,// 注册子组件components: {ChildComponent}, methods: {handleParentEvent(data) {// 处理自定义事件的逻辑console.log(data); // 输出Hello, World!}}
}
/script 使用二$emit update 和 .sync 修饰符
作用.sync可以帮我们实现父组件向子组件传递的数据的双向绑定所以子组件接收到数据后可以直接修改并且会同时修改父组件的数据
// 父组件
template//给子组件传值时使用.sync修饰符child :page.syncpage/child
/template
script
export default {data(){return {page:1}}
}
/script//子组件中
script
export default {props:[page],computed(){// 当我们在子组件里修改 currentPage 时父组件的 page 也会随之改变 currentPage {get(){return this.page},set(newVal){//$emit update 修改父组件中的数据this.$emit(update:page, newVal)}}}
}
/script相当于省略了父组件给子组件多传递一个修改数据的方法
// 带 .sync 修饰符
children :selectNode.syncnode /// 无 .sync 修饰符等同于
children :selectNodenode update:selectNodenode$event / 实现子组件与父组件双向绑定的【sync】修饰符其实sync这个修饰符是vue1.0就有的它可以实现父子组件的双向绑定但是Vue2.0被移除了直到2.3.0版本发布后又重新开始启用由于数据安全问题后来vue3.x后又被重新取消了。 【.sync】可以很轻松的实现子组件同步修改父组件的值如果子组件想修改父组件的值推荐在子组件中以 update:my-prop-name 的模式触发事件取而代之也就是这样
父组件 text-documentv-bind:titledoc.titlev-on:update:titledoc.title $event
/text-document 子组件this.$emit(update:title,newTitle)
而上边的 v-on:update:titledoc.title $event本质上就可以用sync这个语法糖来表示.sync后面紧接的就是父组件中需要被改变的值看下边的例子
父组件templatedivchild-com :value.synctext /child-com/div
/template
scriptexport default{data(){return {text:父组件的值,}},}
/script
子组件中修改父组件的值templatediv clickpost/div
/template
scriptexport default{methods:{post(){this.$emit(update:value,子组件的值)}}}
/script