ホームページ  >  記事  >  ウェブフロントエンド  >  コンポーネント間で通信するにはどうすればよいですか? Vue コンポーネントの通信メソッドの一覧 (収集する価値がある)

コンポーネント間で通信するにはどうすればよいですか? Vue コンポーネントの通信メソッドの一覧 (収集する価値がある)

青灯夜游
青灯夜游転載
2022-08-19 20:04:021351ブラウズ

Vueコンポーネント間で通信するにはどうすればよいですか?この記事では、Vue2 と Vue3 の 10 個のコンポーネント通信方法を整理します。

コンポーネント間で通信するにはどうすればよいですか? Vue コンポーネントの通信メソッドの一覧 (収集する価値がある)

Vue ではコンポーネントを通信する方法が多数あり、Vue2 と Vue3 の実装には多くの違いがあります。この記事では オプションの API## を使用します。 # APIsetup を組み合わせた 3 つの異なる実装方法は、Vue2 と Vue3 のコンポーネント通信方法を包括的に紹介します。実装する通信方式は下表のとおりです。 (学習ビデオ共有: vue ビデオ チュートリアル )

方法Vue2Vue3 父から息子への受け渡しpropsprops 息子から父への受け渡し$emitemits 父から息子へ$attrsattrs息子から父親へ$リスナー父親から息子子から親へ# #子コンポーネントは親コンポーネントにアクセスします#$parent#親コンポーネントは子コンポーネントにアクセスしますなし##$refexpose&refブラザーが値を渡すイベントバスmitt

props

Props は、コンポーネント通信で最も一般的に使用される通信方法の 1 つです。親コンポーネントは v-bind を介して渡され、子コンポーネントは props を介して受信されます。その実装メソッドは次の 3 つです。

  • オプションの API
//父组件

<template>
  <div>
    <Child :msg="parentMsg" />
  </div>
</template>
<script>
import Child from './Child'
export default {
  components:{
    Child
  },
  data() {
    return {
      parentMsg: '父组件信息'
    }
  }
}
</script>


//子组件

<template>
  <div>
    {{msg}}
  </div>
</template>
<script>
export default {
  props:['msg']
}
</script>
  • Combined Api
//父组件

<template>
  <div>
    <Child :msg="parentMsg" />
  </div>
</template>
<script>
import { ref,defineComponent } from 'vue'
import Child from './Child.vue'
export default defineComponent({
  components:{
    Child
  },
  setup() {
    const parentMsg = ref('父组件信息')
    return {
      parentMsg
    };
  },
});
</script>

//子组件

<template>
    <div>
        {{ parentMsg }}
    </div>
</template>
<script>
import { defineComponent,toRef } from "vue";
export default defineComponent({
    props: ["msg"],// 如果这行不写,下面就接收不到
    setup(props) {
        console.log(props.msg) //父组件信息
        let parentMsg = toRef(props, 'msg')
        return {
            parentMsg
        };
    },
});
</script>
  • セットアップ構文シュガー
//父组件

<template>
  <div>
    <Child :msg="parentMsg" />
  </div>
</template>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const parentMsg = ref('父组件信息')
</script>

//子组件

<template>
    <div>
        {{ parentMsg }}
    </div>
</template>
<script setup>
import { toRef, defineProps } from "vue";
const props = defineProps(["msg"]);
console.log(props.msg) //父组件信息
let parentMsg = toRef(props, 'msg')
</script>

Note

プロパティ内のデータ フローは単一の項目ですつまり、サブコンポーネントは親コンポーネントによって渡された値を変更できません。

結合された API で、他の変数を使用して子コンポーネントの props の値を受け取りたい場合は、toRef を使用する必要があります。 props 内のプロパティをレスポンシブに変換します。

emit

子コンポーネントは、emit を通じてイベントを発行し、いくつかのパラメーターを渡すことができ、親コンポーネントは v-on

    を通じてこのイベントを監視します。
  • オプション API
//父组件

<template>
  <div>
    <Child @sendMsg="getFromChild" />
  </div>
</template>
<script>
import Child from './Child'
export default {
  components:{
    Child
  },
  methods: {
    getFromChild(val) {
      console.log(val) //我是子组件数据
    }
  }
}
</script>

// 子组件

<template>
  <div>
    <button @click="sendFun">send</button>
  </div>
</template>
<script>
export default {
  methods:{
    sendFun(){
      this.$emit('sendMsg','我是子组件数据')
    }
  }
}
</script>
  • 結合 API
//父组件

<template>
  <div>
    <Child @sendMsg="getFromChild" />
  </div>
</template>
<script>
import Child from './Child'
import { defineComponent } from "vue";
export default defineComponent({
  components: {
    Child
  },
  setup() {
    const getFromChild = (val) => {
      console.log(val) //我是子组件数据
    }
    return {
      getFromChild
    };
  },
});
</script>

//子组件

<template>
    <div>
        <button @click="sendFun">send</button>
    </div>
</template>

<script>
import { defineComponent } from "vue";
export default defineComponent({
    emits: ['sendMsg'],
    setup(props, ctx) {
        const sendFun = () => {
            ctx.emit('sendMsg', '我是子组件数据')
        }
        return {
            sendFun
        };
    },
});
</script>
  • セットアップ構文シュガー
//父组件

<template>
  <div>
    <Child @sendMsg="getFromChild" />
  </div>
</template>
<script setup>
import Child from './Child'
const getFromChild = (val) => {
      console.log(val) //我是子组件数据
    }
</script>

//子组件

<template>
    <div>
        <button @click="sendFun">send</button>
    </div>
</template>
<script setup>
import { defineEmits } from "vue";
const emits = defineEmits(['sendMsg'])
const sendFun = () => {
    emits('sendMsg', '我是子组件数据')
}
</script>

属性およびリスナー

子コンポーネントは $attrs を使用して、props によって渡される属性と属性バインディング属性 (クラスとスタイル) を除く親コンポーネントのすべての属性を取得します。

サブコンポーネントは、$listeners を使用して、Vue3 では使用されなくなった親コンポーネントのすべての v-on イベント リスナー (.native 修飾子を除く) を取得します。しかし、Vue3 の attrs は、親コンポーネント 渡されたプロパティは、親コンポーネント v-on イベント リスナーからも取得できます。

  • オプションの API
//父组件

<template>
  <div>
    <Child @parentFun="parentFun" :msg1="msg1" :msg2="msg2"  />
  </div>
</template>
<script>
import Child from './Child'
export default {
  components:{
    Child
  },
  data(){
    return {
      msg1:'子组件msg1',
      msg2:'子组件msg2'
    }
  },
  methods: {
    parentFun(val) {
      console.log(`父组件方法被调用,获得子组件传值:${val}`)
    }
  }
}
</script>

//子组件

<template>
  <div>
    <button @click="getParentFun">调用父组件方法</button>
  </div>
</template>
<script>
export default {
  methods:{
    getParentFun(){
      this.$listeners.parentFun('我是子组件数据')
    }
  },
  created(){
    //获取父组件中所有绑定属性
    console.log(this.$attrs)  //{"msg1": "子组件msg1","msg2": "子组件msg2"}
    //获取父组件中所有绑定方法    
    console.log(this.$listeners) //{parentFun:f}
  }
}
</script>
  • 複合 API
//父组件

<template>
  <div>
    <Child @parentFun="parentFun" :msg1="msg1" :msg2="msg2" />
  </div>
</template>
<script>
import Child from './Child'
import { defineComponent,ref } from "vue";
export default defineComponent({
  components: {
    Child
  },
  setup() {
    const msg1 = ref('子组件msg1')
    const msg2 = ref('子组件msg2')
    const parentFun = (val) => {
      console.log(`父组件方法被调用,获得子组件传值:${val}`)
    }
    return {
      parentFun,
      msg1,
      msg2
    };
  },
});
</script>

//子组件

<template>
    <div>
        <button @click="getParentFun">调用父组件方法</button>
    </div>
</template>
<script>
import { defineComponent } from "vue";
export default defineComponent({
    emits: ['sendMsg'],
    setup(props, ctx) {
        //获取父组件方法和事件
        console.log(ctx.attrs) //Proxy {"msg1": "子组件msg1","msg2": "子组件msg2"}
        const getParentFun = () => {
            //调用父组件方法
            ctx.attrs.onParentFun('我是子组件数据')
        }
        return {
            getParentFun
        };
    },
});
</script>
  • セットアップ構文 Sugar
//父组件

<template>
  <div>
    <Child @parentFun="parentFun" :msg1="msg1" :msg2="msg2" />
  </div>
</template>
<script setup>
import Child from './Child'
import { ref } from "vue";
const msg1 = ref('子组件msg1')
const msg2 = ref('子组件msg2')
const parentFun = (val) => {
  console.log(`父组件方法被调用,获得子组件传值:${val}`)
}
</script>

//子组件

<template>
    <div>
        <button @click="getParentFun">调用父组件方法</button>
    </div>
</template>
<script setup>
import { useAttrs } from "vue";

const attrs = useAttrs()
//获取父组件方法和事件
console.log(attrs) //Proxy {"msg1": "子组件msg1","msg2": "子组件msg2"}
const getParentFun = () => {
    //调用父组件方法
    attrs.onParentFun('我是子组件数据')
}
</script>

Note

Attrs を使用して Vue3 の親コンポーネント メソッドを呼び出す場合は、 on を追加する必要がありますメソッドの前 (たとえば、parentFun->onParentFun

provide/inject

provide: は、オブジェクト、またはオブジェクトを返す関数です。これには、将来の世代

inject に与えられる属性 (文字列配列またはオブジェクト) が含まれています。親コンポーネントまたは上位レベルのコンポーネントによって提供される値を取得します。この値は、inject

  • オプション API
//父组件
<script>
import Child from './Child'
export default {
  components: {
    Child
  },
  data() {
    return {
      msg1: '子组件msg1',
      msg2: '子组件msg2'
    }
  },
  provide() {
    return {
      msg1: this.msg1,
      msg2: this.msg2
    }
  }
}
</script>

//子组件

<script>
export default {
  inject:['msg1','msg2'],
  created(){
    //获取高层级提供的属性
    console.log(this.msg1) //子组件msg1
    console.log(this.msg2) //子组件msg2
  }
}
</script>
  • 複合型を介して子孫コンポーネントで取得できます。 API
//父组件

<script>
import Child from './Child'
import { ref, defineComponent,provide } from "vue";
export default defineComponent({
  components:{
    Child
  },
  setup() {
    const msg1 = ref('子组件msg1')
    const msg2 = ref('子组件msg2')
    provide("msg1", msg1)
    provide("msg2", msg2)
    return {
      
    }
  },
});
</script>

//子组件

<template>
    <div>
        <button @click="getParentFun">调用父组件方法</button>
    </div>
</template>
<script>
import { inject, defineComponent } from "vue";
export default defineComponent({
    setup() {
        console.log(inject('msg1').value) //子组件msg1
        console.log(inject('msg2').value) //子组件msg2
    },
});
</script>
  • セットアップ構文sugar
//父组件
<script setup>
import Child from './Child'
import { ref,provide } from "vue";
const msg1 = ref('子组件msg1')
const msg2 = ref('子组件msg2')
provide("msg1",msg1)
provide("msg2",msg2)
</script>

//子组件

<script setup>
import { inject } from "vue";
console.log(inject('msg1').value) //子组件msg1
console.log(inject('msg2').value) //子组件msg2
</script>

説明

provide/injectは通常、コンポーネントの深いネスト内にあります。適当に。一般的にコンポーネント開発で使用されます。

parent/children

$parent: 子コンポーネントは親コンポーネントの Vue インスタンスを取得し、親コンポーネントのプロパティやメソッドなどを取得できます。

$children: Parent コンポーネントは、直接の子の配列およびコレクションであるサブコンポーネントの Vue インスタンスを取得しますが、サブコンポーネントの順序は保証されません

  • Vue2
import Child from './Child'
export default {
  components: {
    Child
  },
  created(){
    console.log(this.$children) //[Child实例]
    console.log(this.$parent)//父组件实例
  }
}

Note親コンポーネントによって取得された $children は応答しません

expose&ref

$refs は要素の属性を直接取得でき、サブコンポーネントのインスタンスも直接取得できます。

  • オプションの API
//父组件

<template>
  <div>
    <Child ref="child" />
  </div>
</template>
<script>
import Child from './Child'
export default {
  components: {
    Child
  },
  mounted(){
    //获取子组件属性
    console.log(this.$refs.child.msg) //子组件元素

    //调用子组件方法
    this.$refs.child.childFun('父组件信息')
  }
}
</script>

//子组件 

<template>
  <div>
    <div></div>
  </div>
</template>
<script>
export default {
  data(){
    return {
      msg:'子组件元素'
    }
  },
  methods:{
    childFun(val){
      console.log(`子组件方法被调用,值${val}`)
    }
  }
}
</script>
  • 結合API
//父组件

<template>
  <div>
    <Child ref="child" />
  </div>
</template>
<script>
import Child from './Child'
import { ref, defineComponent, onMounted } from "vue";
export default defineComponent({
  components: {
    Child
  },

  setup() {
    const child = ref() //注意命名需要和template中ref对应
    onMounted(() => {
      //获取子组件属性
      console.log(child.value.msg) //子组件元素

      //调用子组件方法
      child.value.childFun('父组件信息')
    })
    return {
      child //必须return出去 否则获取不到实例
    }
  },
});
</script>

//子组件

<template>
    <div>
    </div>
</template>
<script>
import { defineComponent, ref } from "vue";
export default defineComponent({
    setup() {
        const msg = ref('子组件元素')
        const childFun = (val) => {
            console.log(`子组件方法被调用,值${val}`)
        }
        return {
            msg,
            childFun
        }
    },
});
</script>
  • セットアップ構文シュガー
//父组件

<template>
  <div>
    <Child ref="child" />
  </div>
</template>
<script setup>
import Child from './Child'
import { ref, onMounted } from "vue";
const child = ref() //注意命名需要和template中ref对应
onMounted(() => {
  //获取子组件属性
  console.log(child.value.msg) //子组件元素

  //调用子组件方法
  child.value.childFun('父组件信息')
})
</script>

//子组件

<template>
    <div>
    </div>
</template>
<script setup>
import { ref,defineExpose } from "vue";
const msg = ref('子组件元素')
const childFun = (val) => {
    console.log(`子组件方法被调用,值${val}`)
}
//必须暴露出去父组件才会获取到
defineExpose({
    childFun,
    msg
})
</script>

Note

ref を介してサブコンポーネント インスタンスを取得するには、その後で取得する必要があります。ページがマウントされました。

セットアップ構文シュガーを使用する場合、子コンポーネントは、

EventBus/mitt

兄弟を取得するために、要素またはメソッドを親コンポーネントに公開する必要があります。コンポーネント通信 イベント センター EventBus を通じて実装でき、イベントを監視、トリガー、破棄するための新しい Vue インスタンスを作成します。

Vue3 には EventBus 兄弟コンポーネント通信はありませんが、代わりのソリューション mitt.js があり、原則は依然として EventBus です

  • オプション API
//组件1
<template>
  <div>
    <button @click="sendMsg">传值</button>
  </div>
</template>
<script>
import Bus from './bus.js'
export default {
  data(){
    return {
      msg:'子组件元素'
    }
  },
  methods:{
    sendMsg(){
      Bus.$emit('sendMsg','兄弟的值')
    }
  }
}
</script>

//组件2

<template>
  <div>
    组件2
  </div>
</template>
<script>
import Bus from './bus.js'
export default {
  created(){
   Bus.$on('sendMsg',(val)=>{
    console.log(val);//兄弟的值
   })
  }
}
</script>

//bus.js

import Vue from "vue"
export default new Vue()
  • 結合 API

最初に mitt

npm i mitt -S

をインストールし、次に bus.js のような新しい API を作成しますVue2mitt.jsFile

mitt.js

import mitt from 'mitt'
const Mitt = mitt()
export default Mitt
//组件1
<template>
     <button @click="sendMsg">传值</button>
</template>
<script>
import { defineComponent } from "vue";
import Mitt from './mitt.js'
export default defineComponent({
    setup() {
        const sendMsg = () => {
            Mitt.emit('sendMsg','兄弟的值')
        }
        return {
           sendMsg
        }
    },
});
</script>

//组件2
<template>
  <div>
    组件2
  </div>
</template>
<script>
import { defineComponent, onUnmounted } from "vue";
import Mitt from './mitt.js'
export default defineComponent({
  setup() {
    const getMsg = (val) => {
      console.log(val);//兄弟的值
    }
    Mitt.on('sendMsg', getMsg)
    onUnmounted(() => {
      //组件销毁 移除监听
      Mitt.off('sendMsg', getMsg)
    })

  },
});
</script>
  • セットアップ構文sugar
//组件1

<template>
    <button @click="sendMsg">传值</button>
</template>
<script setup>
import Mitt from './mitt.js'
const sendMsg = () => {
    Mitt.emit('sendMsg', '兄弟的值')
}
</script>

//组件2

<template>
  <div>
    组件2
  </div>
</template>
<script setup>
import { onUnmounted } from "vue";
import Mitt from './mitt.js'
const getMsg = (val) => {
  console.log(val);//兄弟的值
}
Mitt.on('sendMsg', getMsg)
onUnmounted(() => {
  //组件销毁 移除监听
  Mitt.off('sendMsg', getMsg)
})
</script>

最後に書く

実際、コンポーネントは Vuex または Pinia 状態管理ツールと通信することもできます (ただし、これはコンポーネント間の通信には一般的に推奨されません。コンポーネントが再利用できないという問題が発生するためです)。 Vuex と Pinia の使用方法については、この記事を参照してください。 Pinia と Vuex

(学習ビデオ共有: Web フロントエンド開発, #) ## 基本的なプログラミングのビデオ )

##なし(attrsモードにマージ)
provide provide
inject inject
None #$children
親コンポーネントが子コンポーネントにアクセス

以上がコンポーネント間で通信するにはどうすればよいですか? Vue コンポーネントの通信メソッドの一覧 (収集する価値がある)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はjuejin.cnで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。