1. $refs的使用
在使用vue框架的时候,尽量不要去操作原生的DOM
但是某些情况下,在组件中想要直接获取到元素对象或者子组件实例,vue提供了$refs
1.1 获取元素
点击查看代码
<template>
<div class="app">
<h2 ref="title">{{ title }}</h2>
<button @click="getTitle">获取title元素</button>
</div>
</template>
<script>
export default {
data(){
return {
title: "hello world"
}
},
methods: {
getTitle(){
console.log(this.$refs.title);
}
}
}
</script>
<style scoped>
</style>
1.2 获取组件实例
父组件可以获取到 组件的实例,那么就可以直接调用子组件中的方法
2. 动态组件的实现
2.1 第一种方法: v-if的逻辑来实现
点击查看代码
<template>
<div class="app">
<div>
<template v-for="(item,index) in List" :key="index">
<button :class="{ active: CurrentIndex === index }" @click="handle(index)">{{ item }}</button>
</template>
</div>
<div>
<template v-if="CurrentIndex === 0">
<About></About>
</template>
<template v-else-if="CurrentIndex === 1">
<Home></Home>
</template>
<template v-else-if="CurrentIndex === 2">
<Play></Play>
</template>
</div>
</div>
</template>
<script>
import About from './views/About.vue'
import Home from './views/Home.vue'
import Play from './views/Play.vue'
export default {
components: {
About,
Home,
Play
},
data(){
return {
List: ["About","Home","Play"],
CurrentIndex: 0
}
},
methods: {
handle(index){
this.CurrentIndex = index
}
}
}
</script>
<style scoped>
.active {
color: red;
}
</style>
这种虽然可以实现,但是比较复杂,当组件过多的时候,不是很好
2.2 第二种方法: vue提供的动态组件来实现切换
动态组件是使用component组件,通过一个特殊的属性 is 来实现
点击查看代码
<template>
<div class="app">
<div>
<template v-for="(item,index) in List" :key="index">
<button :class="{ active: CurrentIndex === index }" @click="handle(index)">{{ item }}</button>
</template>
</div>
<component :is="List[CurrentIndex]"></component>
</div>
</template>
<script>
import About from './views/About.vue'
import Home from './views/Home.vue'
import Play from './views/Play.vue'
export default {
components: {
About,
Home,
Play
},
data(){
return {
List: ["About","Home","Play"],
CurrentIndex: 0
}
},
methods: {
handle(index){
this.CurrentIndex = index
}
}
}
</script>
<style scoped>
.active {
color: red;
}
</style>
2.3 动态组件的传值
只是需要将属性和监听事件放到component上来使用
3. keepalive的使用
3.1 测试代码
app.vue
点击查看代码
<template>
<div id="app">
<div>
<template v-for="(item,index) in List" :key="index">
<button @click=handle(index)>{{ item }}</button>
</template>
</div>
<component :is="List[CurrentIndex]"></component>
</div>
</template>
<script>
import Home from './components/Home.vue'
import About from './components/About.vue'
export default {
components: {
Home,
About
},
data(){
return {
List: ["home","about"],
CurrentIndex: 0
}
},
methods: {
handle(index){
this.CurrentIndex = index
}
}
}
</script>
<style scoped>
</style>
原文地址:http://www.cnblogs.com/yufenchi/p/16792882.html
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,请务用于商业用途!
3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员!
8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载
声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性