vue | tab导航

之前看bootstrap的时候就觉得它的轮播导航很好用,最近又在vue官网看到个tab导航,觉得很不错

网址https://jsfiddle.net/chrisvfritz/Lp20op9o/

然后被我用vue-cli改了改(其实就是复制粘贴),像个正常的页面了,还添加了我自己的信息(逃 

github地址[vue-tabpage]https://github.com/Saber2pr/vue-tabpage

 说说它实现的原理

首先是模板<template>

<div id="dynamic-component-demo">
  <button
    v-for="tab in tabs"
    v-bind:key="tab"
    v-bind:class="['tab-button', { active: currentTab === tab }]"
    v-on:click="currentTab = tab"
  >{{ tab }}</button>

  <keep-alive>
    <component
      v-bind:is="currentTabComponent"
      class="tab"
    ></component>
  </keep-alive>
</div>

用了个button标签,内容绑定了tab的值,

使用v-for来遍历tabs,key取到每个元素tab,如果tab是currentTab,则它的css样式active=true,否则false,

然后绑定click事件,触发后更新currentTab的值为tab。

这里的tabs和currentTab都是脚本所创建的对象,tabs是个数组对象,currentTab是字符串对象,tab是临时创建的对象。

然后是脚本

​
Vue.component('tab-posts', { 
  data: function () {
  	return {
      posts: [
        { 
          id: 1, 
          title: 'Cat Ipsum',
          content: "..."
        },
        { 
          id: 2, 
          title: 'Hipster Ipsum',
          content: '...'
        },
        { 
          id: 3, 
          title: 'Cupcake Ipsum',
          content: '...'
        }
      ],
      selectedPost: null
    }
  },
	template: `
  	<div class="posts-tab">
      <ul class="posts-sidebar">
        <li
          v-for="post in posts"
          v-bind:key="post.id"
          v-bind:class="{ selected: post === selectedPost }"
					v-on:click="selectedPost = post"
        >
          {{ post.title }}
        </li>
      </ul>
      <div class="selected-post-container">
      	<div 
        	v-if="selectedPost"
          class="selected-post"
        >
          <h3>{{ selectedPost.title }}</h3>
          <div v-html="selectedPost.content"></div>
        </div>
        <strong v-else>
          Click on a blog title to the left to view it.
        </strong>
      </div>
    </div>
  `
})

Vue.component('tab-archive', { 
	template: '<div>Archive component</div>' 
})

new Vue({
  el: '#dynamic-component-demo',
  data: {
    currentTab: 'Posts',
    tabs: ['Posts', 'Archive']
  },
  computed: {
    currentTabComponent: function () {
      return 'tab-' + this.currentTab.toLowerCase()
    }
  }
})

​

脚本里先不看上面的vue.component,先看下面这个new 的vue对象,

首先绑定到dom,

设置了两个属性,currentTab和tabs,

然后设置了一个计算属性currentTabComponent,它等于‘tab-’ + this.currentTab.toLowerCase(),这样每次currentTab变化时可以获得对应的currentTabComponent

toLowerCase方法是将currentTab的字母转为小写。

接下来再看上面的两个vue.component,

定义了两个组件tab-posts和tab-archive,这两个组件仔细看,其实也是两个tabs组件,把小组件写到了对象的template属性里,原理和最下面这个差不多,由于属性不需要额外计算,所以没用Computed 。

猜你喜欢

转载自blog.csdn.net/u011607490/article/details/82957561
今日推荐