vue修改父组件值的方法:1、通过props的方式,将父组件的方法传递到子组件,在子组件中通过props接收;2、通过“this.$emit”触发父组件方法实现修改;3、通过“this.$parent”直接触发父组件修改即可。
本教程操作环境:windows10系统、vue 3版、dell g3电脑。
vue怎么修改父组件值?
vue中子组件更改父组件数据
因为vue是单项数据流,所以没办法直接在子组件中去修改父组件里面的数据,vue提倡单项数据流,为了防止项目过于复杂时,导致数据流难以理解。引用vue的官网的话:父系 prop 的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外改变父及组件的状态,从而导致你的应用的数据流向难以理解。所以在项目开发过程中,我们总是通过子组件触发父组件中方法的方式,通过父组件的方法,更改父组件的数据。
一、props传递方法
通过props的方式,将父组件的方法传递到子组件,在子组件中通过props接收,可以在当前组件的实例上直接触发父组件的方法,从而实现子组件更改父组件的值。同事也可以将子组件的数据,以参数的形式发送给父组件。
由于代码不多,就暂且全部展示,仅需关心相关事件就可以
//父组件,设置更改自己数据的方法,将该方法传递给子组件<template> <div> <h1>我是父组件</h1> <helloworld :msg="msg" :changemsg="changemsg"/> </div></template> <script>import helloworld from '@/components/helloworld.vue' export default { name: 'home', components: { helloworld }, methods:{ changemsg(text,num){ console.log(text,num); this.msg=this.msg+1 } }, data(){ return{ msg:1 } }}</script> //子组件,接收父组件传递过来的方法,通过props接收到的方法和数据,在组件实例上可以直接获取和触发<template> <div> <h1>我是子组件<button @click="changefatherdata">点我更改父组件数据</button></h1> <h1>父组件数据:{{msg}}</h1> </div></template> <script>export default { name: 'helloworld', props: { msg: number, changemsg:function }, data(){ return{ text:"我是子组件数据,我要发送给父组件", num:12 } }, methods:{ changefatherdata(){ this.changemsg(this.text,this.num) } },}</script> <style scoped> </style>
二、通过this.$emit触发父组件方法实现
在父组件中自定义一个方法,然后传递给子组件,子组件通过this.$emit直接触发父组件中的数据,实现父子组件通信。子组件触发事件,父组件监听事件。
//父组件,将定义的方法传递给子元素<template> <div> <h1>我是父组件</h1> <helloworld :msg="msg" @changemsg="changemsg"/> </div></template> <script>import helloworld from '@/components/helloworld.vue' export default { name: 'home', components: { helloworld }, methods:{ changemsg(text,num){ console.log(text,num); this.msg=this.msg+1 } }, data(){ return{ msg:1 } }}</script> //子组件,通过this.$emit触发父组件方法,更改父组件数据,同时可以进行数据传值<template> <div> <h1>我是子组件<button @click="changefatherdata">点我更改父组件数据</button></h1> <h1>父组件数据:{{msg}}</h1> </div></template> <script>export default { name: 'helloworld', props: { msg: number, }, data(){ return{ text:"我是子组件数据,我要发送给父组件", num:12 } }, methods:{ changefatherdata(){ this.$emit('changemsg',this.text,this.num) } },}</script> <style scoped> </style>
三、子组件通过this.$parent直接触发父组件(代码简洁,推荐使用)
子组件直接触发父组件事件,无需进行方法的传递、接收,以及事件的定义。
//父组件,声明需要的方法<template> <div> <h1>我是父组件</h1> <helloworld :msg="msg"/> </div></template> <script>import helloworld from '@/components/helloworld.vue' export default { name: 'home', components: { helloworld }, methods:{ changemsg(text,num){ console.log(text,num); this.msg=this.msg+1 } }, data(){ return{ msg:1 } }}</script> //子组件,this.$parent直接触发父组件方法<template> <div> <h1>我是子组件<button @click="changefatherdata">点我更改父组件数据</button></h1> <h1>父组件数据:{{msg}}</h1> </div></template> <script>export default { name: 'helloworld', props: { msg: number, }, data(){ return{ text:"我是子组件数据,我要发送给父组件", num:12 } }, methods:{ changefatherdata(){ this.$parent.changemsg(this.text,this.num) } },}</script> <style scoped> </style>
推荐学习:《vue.js视频教程》
以上就是vue怎么修改父组件值的详细内容。