美文网首页关于vue
slot切换局部页面内容,真的超级好用——登陆页面

slot切换局部页面内容,真的超级好用——登陆页面

作者: 简小园 | 来源:发表于2019-05-10 11:09 被阅读0次

用vue开发前端项目,路由必不可少,还有一个超好用的局部内容切换工具——插槽(slot)

写在前面

slot是vue提供的内置组件,指的是:子组件留坑,父组件填写内容。
也就是说,插槽显不显示、怎样显示是由父组件来控制的,而插槽在哪里显示就由子组件来进行控制。

结构

  • 子组件
    <slot name="slotname"/>
  • 父组件
    <div slot="slotname">我是插槽</div>

没错,老师就这么讲的,当时的我只是知道有这样一个东西,并没有实际应用,直到……

哈哈,话不多说,上例子:

敲黑板

例如做一个登陆页面,它有两部分哦,分为密码登陆和验证码登陆,大概是这个样子


login.gif
  1. 子组件留坑:
<section>
   <!--头部切换键,: 是v-bind的语法糖-->
    <ul>
      <li v-for="tab,index in tabs" :class="index==cur?'active':''" @click="cur=index">{{tab.title}}</li>
    </ul>
  <!--留坑-->
    <div v-for="tab,index in tabs" :style="{display: index==cur?'block':'none'}">
      <slot :name="tab.slotname"/>
    </div>
</section>

<script>
export default {
  props: ['tabs'],
  data(){
    return {
      cur: 0
    }
  }
}
</script>
  1. 父组件填充内容:
<Loginx :tabs="tabs">
    <!-- 密码登录 -->
    <template slot="tab1">
        <div class="form-group">
          <input type="text" class="form-control" id="account" placeholder="手机号/邮箱">
        </div>
        <div class="form-group">
          <input type="password" class="form-control" id="pwd" placeholder="密码">
        </div>
        <div class="form-group">
          <button class="btn" @click="pwdLogin">登录</button>
          <router-link to="/reg" class="reg">点击注册</router-link>
        </div>
      </template>
      <!-- 验证码登录 -->
      <template slot="tab2">
        <div class="form-group">
          <input type="text" class="form-control" id="account2" placeholder="手机号/邮箱">
        </div>
        <div class="form-group">
          <input type="text" class="form-control code" id="code" placeholder="验证码">
          <button class="getCode" @click="getCode">获取验证码</button>
        </div>
       <div class="form-group">
         <button class="btn" @click="codeLogin">登录</button>
         <router-link to="/reg" class="reg">点击注册</router-link>
      </div>
    </template>
</Loginx>

<script>
import Loginx from '@/components/loginx';

export default {
  name: 'Login',
  components: { Header,Loginx },
  data(){
    return {
      tabs: [
        {title: '密码登录', slotname: 'tab1'},
        {title: '验证码登录', slotname: 'tab2'}
      ]
    }
  }
}
</script>

写在后面

用vue开发前端,slot一定是个重要的角色,aaa~继续学习!!!

相关文章

网友评论

    本文标题:slot切换局部页面内容,真的超级好用——登陆页面

    本文链接:https://www.haomeiwen.com/subject/ojtboqtx.html