1. 程式人生 > 其它 >Vue3學習之元件傳值

Vue3學習之元件傳值

技術標籤:VueTypeScriptvue

目錄

前言:

一:父子元件傳值

1.emit(子元件)

2:props

3:provide和inject (與vue2用法一樣)

二:總結


前言:

眾所周知,Vue單項資料流,在vue2.x版本中,父子元件傳值都通過,props和emit傳值,但是在vue3中取消了this上下文,那this.$emit咋搞呢?接下來就是記錄學習vue3元件傳值的方法,淦就完了,奧利給~

一:父子元件傳值

1.emit

子元件傳值

<template>
  <button @click="childEmit">傳值</button>
</template>

<script>
export default {
  props: {
    count: Number
  },
  emits: ['child-emit'],
  setup (props, { emit }) {
    const childEmit = () => {
      emit('child-emit', '我是子元件')
    }
    return {
      childEmit
    }
  }
}
</script>

<style lang="scss" scoped></style>

父元件接收

<template>
  <div class="home">
    <HomeChild @child-emit="parentEmit"></HomeChild>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import HomeChild from './HomeChild.vue'
export default defineComponent({
  name: 'Home',
  components: { HomeChild },
  setup () {
    const parentEmit = (val: string) => {
      console.log('setup ~ val', val)
    }
    return {
      parentEmit
    }
  }
})
</script>

來看下結果

2:props

子元件接收,通過props接收,想要使用的話,就得使用props

<template>
  {{ parentValue }}
</template>

<script>
export default {
  props: {
    parentValue: String
  },
  setup (props, { emit }) {
    console.log('parentValue', props.parentValue)
  }
}
</script>

<style lang="scss" scoped></style>

父元件,還和vue2一樣,通過v-bind:名字給子元件傳值

<template>
  <div class="home">
    父元件:{{ parentVal }}
    <div>------------------------</div>
    子元件:<HomeChild :parentValue="parentVal"></HomeChild>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import HomeChild from './HomeChild.vue'
export default defineComponent({
  name: 'Home',
  components: { HomeChild },
  setup () {
    const parentVal = ref('我是父元件的值')
    return {
      parentVal
    }
  }
})
</script>

3:provide和inject (與vue2用法一樣)

使用ref來保證provide和inject之間值的響應: 如果注入一個響應式物件,則它的狀態變化也可以被偵聽

底層元件,通過reject注入

<template> user:{{ user.name}} </template>

<script>
import { inject, ref } from 'vue'
export default {
  props: {
    parentValue: String
  },
  setup () {
    const user = inject('userProp', ref('ailis'))
    return {
      user
    }
  }
}
</script>

<style lang="scss" scoped></style>

頂層元件,通過provide提供變數

<template>
  <div class="home">父元件:<HomeChild></HomeChild></div>
</template>

<script lang="ts">
import { defineComponent, provide, reactive } from 'vue'
import HomeChild from './HomeChild.vue'
export default defineComponent({
  name: 'Home',
  components: { HomeChild },
  setup () {
    const user = reactive({
      name: 'john'
    })
    provide('userProp', user)
    return {
      user
    }
  }
})
</script>

二:總結

provide,inject和props,emit的區別點在於:

props,emit只侷限於父子元件的傳值,如果巢狀太深,就變得很繁瑣,複雜

provide,inject就沒有這一限制,無論元件巢狀多深,都可以遊刃有餘