最近在研究vue.js,總體來說還算可以,但是在web開發群里有一些人問在單文件組件開發模式中非父子組件如何傳值的問題,今天在這里講講,希望對大家有所幫助!
在官網api中的這段講解很少,也很模糊;官網中說明如下:
非父子組件通信:
有時候兩個組件也需要通信 (非父子關系)。在簡單的場景下,可以使用一個空的 Vue 實例作為中央事件總線:
var bus = new Vue();// 觸發組件 A 中的事件bus.$emit('id-selected', 1)// 在組件 B 創建的鉤子中監聽事件bus.$on('id-selected', function (id) { // ...})那么這一段在單文件組件開發模式中具體怎么用呢?
首先在main.js中加入data,如下:
new Vue({ el: '#app', router, template: '<App/>', components: { App }, data:{ bus:new Vue() }})如何獲取到這個空的vue對象 bus呢.在組件里面直接調用這個this.$root
<template> <div class="title" @click="change(msg)">{{ msg }}</div></template><script> export default { name: 'first', data() {  return {  msg: '我是首頁'  } }, methods: {  change(text) {  this.$root.bus.$emit("hehe", text)  } } }</script>然后在另一個組件內調用on事件接收,當然在組件銷毀時解除綁定,使用on事件接收,當然在組件銷毀時解除綁定,使用off方法
<template> <h1>{{ msg }}</h1></template><script> export default { name: 'second', data() {  return {  msg: '我是第二頁'  } }, created() {  let that = this;  this.$root.bus.$on("hehe", function (t) {  that.msg = that.msg + t  }) } }</script>然后點擊的時候就能傳遞值了,還等什么,快來試試吧!
以上這篇vue.js單文件組件中非父子組件的傳值實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持錯新站長站。
新聞熱點
疑難解答
圖片精選