日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

vue组件通讯

發(fā)布時間:2025/3/20 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vue组件通讯 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2019獨角獸企業(yè)重金招聘Python工程師標準>>>

vue組件通訊

一、父 -> 組件之間的通訊:

  • 方式:通過props屬性來傳遞數據

  • 注意:屬性的值必須在組件中通過props屬性顯示指定,否則,不會生效

  • 說明:傳遞過來的props屬性的用法與data屬性的用法相同

// demo1:傳遞普通字符串 // 父組件定義傳遞參數 <hello msg="120"></hello> <hello my-msg="'abc'"></hello>// 子組件中相應接收 <script>components: {hello: {// 顯式創(chuàng)建props及其傳遞過來的屬性props: ['msg', 'myMsg'],template: '<h1>這是 hello 組件,這是消息:{{msg}} --- {{myMsg}}</h1>'}} </script>// demo2傳遞對象或數組 // 父組件定義傳遞參數 <template><office :messageObj='message'></office> </template>export default {data() {return {message:{tabs:1,ids:['31','32']},}}}// 子組件中相應接收 <script>export default {data() {return {props:['messageObj']}}} </script>

二、子組件到父組件

  • 方式:父組件給子組件傳遞一個函數,由子組件調用這個函數
  • 說明:借助vue中的自定義事件(v-on:cunstomFn="fn")
  • $emit():觸發(fā)事件
<hello @pfn="parentFn"></hello><script>new Vue({methods: {// 父組件:提供方法parentFn(data) {console.log('父組件:', data)}}})Vue.component('hello', {template: '<button @click="fn">按鈕</button>',methods: {// 子組件:通過$emit調用fn() {this.$emit('pfn', '這是子組件傳遞給父組件的數據')}}}) </script>

三、非父子組件通訊

在簡單的場景下,可以使用一個空的 Vue 實例作為事件總線

  • $on():綁定事件
var bus = new Vue()// 觸發(fā)組件 A 中的事件 bus.$emit('id-selected', 1)// 在組件 B 創(chuàng)建的鉤子中監(jiān)聽事件 bus.$on('id-selected', function (id) {// ... })
  • 示例:組件A ---> 組件B
<!-- 組件A: --> <com-a></com-a> <!-- 組件B: --> <com-b></com-b><script>var bus = new Vue()var vm = new Vue({el: '#app',components: {comA: {template: '<button @click="emitFn">告訴B</button>',methods: {emitFn() {bus.$emit('tellComB', '土豆土豆我是南瓜')}}},comB: {template: '<p>組件A告訴我:{{msg}}</p>',data() {return {msg: ''}},created() {bus.$on('tellComB', (msg) => {this.msg = msg})}}}}) </script>

四、動態(tài)組件 - component

  • 作用:渲染一個“元組件”為動態(tài)組件。依 is 的值,來決定哪個組件被渲染。
<!-- 動態(tài)組件由 vm 實例的屬性值 `componentId` 控制 --> <component :is="componentId"></component><script> // 兩個組件: Vue.component('home', {template: '<h1>這是 Home 組件</h1>' }) Vue.component('login', {template: '<h1>這是 Login 組件</h1>' })data: {componentId: 'home' } </script>

五、獲取子組件,并且可以使用其中的屬性和方法

<body><div id="app"><!-- 通過給 html元素 添加一個特殊的 ref 屬性,將來就可以直接通過 $refs.dv 來獲取到當前的DOM對象 --><!-- <div ref="dv"></div> --><hello ref="he"></hello></div><script src="./vue.js"></script><script>var vm = new Vue({el: '#app',data: {},components: {hello: {template: `<h1>這是 Hello 組件</h1>`,data() {return {msg: '這是 組件Hello 中的msg 屬性'}}}},created() {// 為什么在 created 中獲取不到 DOM對象???// console.log(this.$refs.dv);},mounted() {// console.log(this.$refs.dv);// 獲取組件,同時組件中的數據或方法都能夠獲取到// console.log(this.$refs.he);console.log(this.$refs.he.msg);}})</script>

轉載于:https://my.oschina.net/shuaihong/blog/1553764

總結

以上是生活随笔為你收集整理的vue组件通讯的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。