宝哥软件园

用v模型完成vue中组件间的通信

编辑:宝哥软件园 来源:互联网 时间:2021-08-20

以上两种方法都是单向数组传递,那么如何实现两个组件之间的双向传递呢?

也就是说,如果父组件中的值被修改,子组件将被立即更新。

该值在子组件中修改,并在父组件中立即更新。

vue有一个很棒的东西叫v型,可以满足我们的需求。

在使用v-model的过程中,我们仍然需要正常引入子组件,但是将值传递方法改为v-model

父组件

template div { {父文本}} child v-model='父文本'/child//调用子组件并将父文本传递给子组件按钮@ click=' change child ' change child button/button/div/templatescriptimport child from '。/child . vue ';导出默认{ name: '父亲',data() { return {父文本: '我是父文本' };},components: { Child },methods : { change Child(){ this .父文本='父更改文本';} }};/script

子组件

template div p class=' child ' @ click=' change ' { {父文本} }/p//正常使用父文本的值。添加一个方法来修改值/div/templatescriptexportdefault { name : ' child ',model 3360 {//添加一个模型方法来接收由v-model传递的参数prop: '父文本'。//父组件event : ' change child '/event transfer }中变量的传递,props: {父文本3360 {//通常使用props接收父文本类型3360string}的值,data(){ return };},methods: { change(){ this .父文本=' son change the text ' } } }/script在这里报告了一个错误,因为数据流是单向的,但是在这里,子组件不应该直接修改props中的值。

这里不能直接修改,需要迂回修改,在子组件中定义一个我们自己的变量,然后将道具的值赋给我们自己的变量。修改我们自己的变量就可以了。

子组件 - 修改props中的值

模板div p class=' child ' @ click=' change ' { child Text } }/p/div/templatescript export default { name : ' child '、Model : { prop: '父text '、//父组件中变量的传输Event 3360 ' change child '//Event Transmission }、props: {父Text 3360 {Type: String}、Data(){ return { child text : this。父文本//定义自己的变量child text };},methods : { change(){ this . child text=' son change the test ';//修改自己的变量} };

两个组件间更新

,完成上述代码后,您会发现两个组件的内容都发生了变化,但只有自己组件的内容进行了更新。两个组件如何同步更新?

在这里,我需要使用我的Wath方法来监控传递组件的变量

template div p class=' child ' @ click=' change child ' { { child Text } }/p/div/templatescript export default { name : ' child ',Model : {prop: '父text ',//父组件中变量的传输事件: ' change child '///事件传输},prop3360 {父FatherText: { Type: String } },data(){ Return { child text 3360 This。父文本}。},methods : { change child(){ this . child text=' son change the test ';}},watch: {父文本(NewText){//使用父组件中的变量名作为函数名来监控父文本的变化。如果它发生了变化,请在子组件中更改this.childText=newtext的值;},childText(newtext) {//监控子组件中childText的变化,并通知父组件对此进行更新。$ emit ('changechild ',new text);} }};摘要

以上是边肖介绍的vue中组件之间的通信。希望对大家有帮助。如果你有任何问题,请给我留言,边肖会及时回复你。非常感谢您对我们网站的支持!如果你觉得这篇文章对你有帮助,请转载,请注明出处,谢谢!

更多资讯
游戏推荐
更多+