1. 程式人生 > 其它 >【Vue3】元件間通訊

【Vue3】元件間通訊

props

父元件向子元件傳遞資料可以通過 props

<!-- 父元件TodoList.vue -->
<template>
  <todo-item
    v-for="todo in todos"
    :key="todo.id"
    :title="todo.title"
  ></todo-item>
</template>

<script>
import TodoItem from '@/components/TodoItem.vue'

export default {
  name: 'TodoList',
  components: {
    TodoItem
  },
  setup() {
    let todos = reactive(
      {id:1, title:eat},
      {id:2, title:sleep}
    )
    
    return {
      todos
    }
  }
}
</script>
<!-- 子元件TodoItem.vue -->
<template>
  <span>{{todo.title}}</span>
  <button></button>
</template>

<script>
export default {
  name: 'TodoItem',
  props: ['todo']
}
</script>

emit

子元件傳遞資料給父元件

<!-- Parent.vue -->
<template>
  <Child @myClick="myClick"/>
</template>

<script>
// @ is an alias to /src
import Child from '@/components/Child.vue'

export default {
  name: 'Parent',
  components: {
    Child
  },
  setup() {

    const myClick = (value) => console.log(value)

    return {
      myClick
    }
  }
}
</script>
<!-- Child.vue -->
<template>
  <button @click="toParent">click</button>
</template>

<script>
export default {
  name: 'Child',
  setup(props,{emit}) {

    const toParent = () => emit('myClick','come from child')
    
    return {
      toParent
    }
  }
}
</script>

Provide / Inject

當父元件向子孫元件傳遞資料時可以使用一對provideinject

父元件有一個provide選項來提供資料,子元件有一個inject選項來開始使用這些資料。

語法:

provide(name, value)  //property名,property值
 
inject(name, default) //property名,預設值

舉例:

<!-- Parent.vue -->
<template>
  <Child />
</template>

<script>
import Child from './Child.vue'
import { provide, reactive, ref, readonly } from 'vue' //匯入provide

export default {
  name: 'Parent',
  components: {
    Child
  },
  setup() {
    const location = ref('North Pole')
    const geolocation = reactive({
      longitude: 90,
      latitude: 135
    })

    const updateLocation = () => {
      location.value = 'South Pole'
    }

    provide('location', readonly(location)) //提供只讀property
    provide('geolocation', geolocation) //提供了一個響應式property
    provide('updateLocation', updateLocation)  //提供了一個方法
  }
}
</script>
<!-- Child.vue -->
<template>
  <GrandChild />
</template>

<script>
import GrandChild from './GrandChild.vue'

export default {
  name: 'Child',
  components: {
    GrandChild
  }
}
</script>
<!-- GrandChild.vue -->
<script>
import { inject } from 'vue' //匯入inject

export default {
  name: 'GrandChild',
  setup() {
    const userLocation = inject('location', 'The Universe') //注入property
    const userGeolocation = inject('geolocation') //注入property
    const updateUserLocation = inject('updateLocation') //注入方法

    return {
      userLocation,
      userGeolocation,
      updateUserLocation
    }
  }
}
</script>

Vuex

多元件間通訊可以通過 Vuex

具體可看官方文件