如何使組件在Vue.js應用程序中進行通信。
Vue中的組件可以通過各種方式進行通信。
道具
第一種方法是使用道具。
父級通過在組件聲明中添加參數來“傳遞”數據:
<template>
<div>
<Car color="green" />
</div>
</template>
<script>
import Car from ‘./components/Car’
export default {
name: ‘App’,
components: {
Car
}
}
</script>
道具是單向的:從父母到孩子。父母每次更改道具時,都會將新值發送給孩子並重新呈現。
反之則不成立,您絕對不應在子組件內部變異道具。
使用事件從孩子與父母溝通
通過事件,您可以從孩子到父母進行交流:
<script>
export default {
name: 'Car',
methods: {
handleClick: function() {
this.$emit('clickedSomething')
}
}
}
</script>
家長可以使用v-on
指令包含在其模板中的組件時:
<template>
<div>
<Car v-on:clickedSomething="handleClickInParent" />
<!-- or -->
<Car @clickedSomething="handleClickInParent" />
</div>
</template>
<script>
export default {
name: ‘App’,
methods: {
handleClickInParent: function() {
//…
}
}
}
</script>
您當然可以傳遞參數:
<script>
export default {
name: 'Car',
methods: {
handleClick: function() {
this.$emit('clickedSomething', param1, param2)
}
}
}
</script>
並從父級檢索它們:
<template>
<div>
<Car v-on:clickedSomething="handleClickInParent" />
<!-- or -->
<Car @clickedSomething="handleClickInParent" />
</div>
</template>
<script>
export default {
name: ‘App’,
methods: {
handleClickInParent: function(param1, param2) {
//…
}
}
}
</script>
使用事件總線在任何組件之間進行通信
使用事件,您不僅限於兒童與父母之間的關係。
您可以使用所謂的活動巴士。
上面我們用過this.$emit
在組件實例上發出事件。
相反,我們可以做的是在更易於訪問的組件上發出事件。
this.$root
根組件,通常用於此目的。
您也可以創建專用於此作業的Vue組件,然後將其導入所需的位置。
<script>
export default {
name: 'Car',
methods: {
handleClick: function() {
this.$root.$emit('clickedSomething')
}
}
}
</script>
任何其他組件都可以偵聽此事件。您可以在mounted
打回來:
<script>
export default {
name: 'App',
mounted() {
this.$root.$on('clickedSomething', () => {
//...
})
}
}
</script>
備擇方案
這就是Vue開箱即用的功能。
當您超出此範圍時,可以查看威克斯或其他第三方庫。
免費下載我的Vue手冊
更多vue教程:
- Vue.js概述
- Vue.js CLI:學習如何使用它
- Vue.js開發工具
- 為Vue開發配置VS代碼
- 使用Vue.js創建您的第一個應用
- Vue.js單個文件組件
- Vue.js模板和插值
- Vue.js指令
- Vue.js方法
- Vue.js計算屬性
- 使用CSS樣式化Vue.js組件
- Vue.js觀察者
- Vue方法vs觀察者vs計算的屬性
- Vue.js過濾器
- Vue.js組件
- Vue.js插槽
- Vue.js組件道具
- Vue.js活動
- Vue.js組件通信
- Vuex,Vue.js狀態管理器
- Vue,在另一個組件內部使用一個組件
- Vue,如何使用prop作為類名
- 如何將SCSS與Vue.js單個文件組件一起使用
- 在Vue.js中使用Tailwind
- Vue路由器
- 動態顯示Vue組件
- Vue.js備忘單
- 使用Vuex將Vue數據存儲到localStorage
- 如何使用Vue動態應用類
- Vue,如何使用v模型
- Vue,為什麼數據必須是函數
- Roadmap to become a Vue.js developer in 2020