wordpress 500 阿里云seo怎么做最佳
目录
一、概述
二、获取dom
2.1. 具体步骤
2.2. 完整代码
2.2.1. main.js
2.2.2. App.vue
2.3. BaseChart.vue
三、获取组件实例
3.1. 具体步骤
3.2. 完整代码
3.2.1. main.js
3.2.2. App.vue
3.2.3. BaseForm.vue
3.3. 运行效果
一、概述
我们过去在想要获取一个dom元素的时候,一般会使用到document.querySelector('class样式')这种全页面范围的查找方式。如果在页面比较复杂(如有多个组件且可能存在相同样式)的情况下,通过这种方式就获取就难以定位一个dom元素。因此Vue为我们提供了ref和$refs。
querySelector 查找范围 → 整个页面
作用:利用ref和$refs可以用于获取dom元素或组件实例。
特点:查找范围 → 当前组件内 (更精确稳定)
二、获取dom
2.1. 具体步骤
1. 目标标签 – 添加 ref 属性
2. 恰当时机, 通过 this.$refs.xxx, 在当前组件内查找获取目标标签
2.2. 完整代码
2.2.1. main.js
import Vue from 'vue'
import App from './App.vue'Vue.config.productionTip = falsenew Vue({render: h => h(App),
}).$mount('#app')
2.2.2. App.vue
<template><div class="app"><div class="base-chart-box">这是一个捣乱的盒子</div><BaseChart></BaseChart></div>
</template><script>
import BaseChart from './components/BaseChart.vue'
export default {components:{BaseChart}
}
</script><style>
.base-chart-box {width: 300px;height: 200px;
}
</style>
2.3. BaseChart.vue
<template><div class="base-chart-box" ref="baseChartBox">子组件</div>
</template><script>
import * as echarts from 'echarts'export default {mounted() {// 基于准备好的dom,初始化echarts实例// document.querySelector 会查找项目中所有的元素// $refs只会在当前组件查找盒子// var myChart = echarts.init(document.querySelector('.base-chart-box'))var myChart = echarts.init(this.$refs.baseChartBox)// 绘制图表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>
三、获取组件实例
3.1. 具体步骤
作用:利用 ref 和 $refs 可以用于 获取 dom 元素, 或 组件实例
② 获取组件:
1. 目标组件 – 添加 ref 属性
2. 恰当时机, 通过 this.$refs.xxx, 获取目标组件,
就可以调用组件对象里面的方法
3.2. 完整代码
3.2.1. main.js
import Vue from 'vue'
import App from './App.vue'Vue.config.productionTip = falsenew Vue({render: h => h(App),
}).$mount('#app')
3.2.2. App.vue
<template><div class="app"><BaseForm ref="baseForm"></BaseForm><button @click="handleGet">获取数据</button><button @click="handleReset">重置数据</button></div>
</template><script>
import BaseForm from './components/BaseForm.vue'
export default {data () {return {}},methods: {handleGet () {console.log(this.$refs.baseForm.getValues())},handleReset () {this.$refs.baseForm.resetValues()}},components:{BaseForm}
}
</script><style></style>
3.2.3. BaseForm.vue
<template><form action="">账号:<input type="text" v-model="account"/><br><br>密码:<input type="text" v-model="password"/><br><br></form>
</template><script>
export default {data () {return {account: '',password: ''}},methods: {// 1. 收集表单数据,返回一个对象getValues () {return {account: this.account,password: this.password}},// 2. 重置表单resetValues () {this.account = '',this.password = ''}}
}
</script><style scoped>
.base-chart-box {width: 400px;height: 300px;border: 3px solid #000;border-radius: 6px;
}
</style>
3.3. 运行效果
父组件App.vue通过ref和$refs直接调用子组件BaseForm的方法获取和重置数据。