組件間如何通訊,也就成爲了vue中重點知識,組件通訊,涉及到組件之間數據的傳遞、相似NET POST/GET參數傳遞。
Vue基本的三種傳遞方式** (props、\(ref、\)emit)** 組件是 vue.js 最強大的功能之一,而組件實例的做用域是相互獨立的,這就意味着不一樣組件之間的數據沒法相互引用。那麼組件間如何通訊,也就成爲了vue中重點知識了。這篇文章將會經過props、$ref和 $emit 這幾個知識點,來說解如何實現父子組件間通訊。html
prop 着重於數據的傳遞,它並不能調用子組件裏的屬性data和方法methods。適合的場景是從父親給孩子,給了以後就是給了,最適合使用prop,。
$ref 着重於索引,主要用來調用子組件裏的屬性和方法,其實並不擅長數據傳遞,可是也是能夠傳遞參數的。vue
<template> <div> <h1>我是父組件!</h1> <one-chart id="myChart" :height="500px" :width="500px" :chart-option="echartOption" /> <!-- (1)這是子組件---> </div> </template> <script> // (2)引用一會兒組件 位置 import OneChart from '@/components/Charts/OneChart' export default { components: { OneChart }, // (3)註冊一下組件 } </script>
<template> <h3>我是子組件!</h3> </template> <script> import echarts from 'echarts' import resize from './mixins/resize' export default { name: 'OneChart', mixins: [resize], props: { className: { type: String, default: 'chart' }, id: { type: String, default: 'chart' }, width: { type: String, default: '200px' }, height: { type: String, default: '200px' }, chartOption: { type: Object, default: () => [] } }, data() { return { chart: null } }, watch: { chartOption: function() { console.log('我是組件chart watch') console.log(this.chartOption) if (this.chartOption !== undefined && this.chartOption !== null) { this.initChart() } } }, mounted() { console.log('我是組件chart mounted') console.log(this.chartOption) }, beforeDestroy() { if (!this.chart) { return } this.chart.dispose() this.chart = null }, methods: { initChart() { console.log(this) } } } </script>
詳細介紹文檔https://cn.vuejs.org/v2/guide/components-props.html數組
<base-input ref="usernameInput"></base-input>
能夠在父頁面任意的使用,能夠調用子頁面的 methodsecharts
this.$refs.usernameInput.focus() this.$refs.usernameInput.demo('我是參數,任意的那種')
methods: { // 用來從父級組件聚焦輸入框 focus: function () { this.$refs.input.focus() }, demo(data){ console.log(data) } }
<base-input ref="usernameInput" @inputShowMsg="showMsg" ></base-input>
methods: {
// 用來從父級組件聚焦輸入框
focus: function () {
this.$refs.input.focus()
},
showMsg(data){ide
console.log('showMsg') console.log(data) //data 輸出: 我是組件的參數,接收一下啊
}
}ui
### 4.1.2 子頁面
methods: {this
demo(data){
console.log('demo')
console.log(data)
this.$emit('getMessage', '我是組件的參數,接收一下啊')spa
}
}code
### 5.2 擴展知識 - emit 是程序化的事件偵聽器,它能夠被 v-on 偵聽 - 包含了父做用域中的 (不含 .native 修飾器的) v-on 事件監聽器。它能夠經過 v-on="$listeners" 傳入**內部組件**——在建立更高層次的組件時很是有用。