淘寶裝修免費模板有哪些網站網站制作公司咨詢
1.作用
利用ref 和 $refs 可以用于 獲取 dom 元素 或 組件實例,也可以在父組件獲取子組件,從而調用子組件的方法。
2.特點:
查找范圍 → 當前組件內(更精確穩(wěn)定)
3.語法
1.給要獲取的盒子添加ref屬性
<div ref="chartRef">我是渲染圖表的容器</div>
2.獲取時通過 $refs獲取 this.$refs.chartRef 獲取
mounted () {console.log(this.$refs.chartRef)
}
4.注意
之前只用document.querySelect(‘.box’) 獲取的是整個頁面中的盒子,
App.vue
<template>
<div class="box"></div>
<Good></Good>
如果Good.vue中有一個class=“box”,在App中通過document.querySelect(".box")
的方式只能獲取到第一個class="box"的元素。
5.代碼示例
App.vue
<template><div class="app"><BaseChart ref="baseChart"></BaseChart><button @click="changeNumber">更新</button></div>
</template><script>
import BaseChart from './components/BaseChart.vue'
export default {methods:{changeNumber(){this.$refs.baseChart.changeNum()}},components:{BaseChart}
}
</script><style>
</style>
BaseChart.vue
<template><div id="chart"><div class="base-chart-box" ref="baseChartBox">子組件</div><p>{{ number }}</p></div>
</template><script>
// yarn add echarts 或者 npm i echarts
import * as echarts from 'echarts'export default {data(){return {number: 100}},methods:{changeNum(){this.number = 200}},mounted() {// 基于準備好的dom,初始化echarts實例var myChart = echarts.init(document.querySelect('.base-chart-box'))// 繪制圖表myChart.setOption({title: {text: 'ECharts 入門示例',},tooltip: {},xAxis: {data: ['襯衫', '羊毛衫', '雪紡衫', '褲子', '高跟鞋', '襪子'],},yAxis: {},series: [{name: '銷量',type: 'bar',data: [5, 20, 36, 10, 10, 20],},],})},
}
</script><style scoped>
.base-chart-box {width: 400px;height: 300px;border: 3px solid #000;border-radius: 6px;
}
</style>
示例代碼在父組件中直接調用子組件的方法進行數(shù)字的更新。