展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

vite2构建vue3,集成sass、实现子组件切换

npm init @vitejs/app
cd demo01
npm install
npm run dev

  • 集成vue router
cnpm install vue-router@next --save 

  • view目录下新建一个子组件DemoManage.vue

  • router目录下新建index.js

import {createRouter, createWebHashHistory} from 'vue-router';
import DemoManage from "../view/DemoManage.vue";
const routes = [
    { path: "/demoManage", component: DemoManage },
]
export default  createRouter({
    history: createWebHashHistory(),
    routes // short for `routes: routes`
})

  • 将路由出口放到根组件App.vue中
<router-view></router-view>
  • 在项目入口main.js中挂在router
import { createApp } from 'vue'
import App from './App.vue'
// router
import router from './router/index'

const app = createApp(App)
app.use(router)
app.mount('#app')
npm install --save-dev sass
  • 配置vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  // 配置sass
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `$injectedColor: orange;`
      }
    }
  }
})

  • 实现子组件切换

  • src/components/dynamic目录下新建子组件

  • DemoManage.vue作为父组件引入刚才新建的子组件,实现子组件切换

<template>
  <div class="page">
    <div class="button">
      <span @click="show(1)"
            :class="index===1? 'active':''">组件一</span>
      <span @click="show(2)"
            :class="index===2? 'active':''">组件二</span>
      <span @click="show(3)"
            :class="index===3? 'active':''">组件三</span>
    </div>
    <div class="tab_content">
      <keep-alive>
        <component :is="comp"
                   v-show="isShow"></component>
      </keep-alive>
    </div>
  </div>
</template>
<script>
import one from '../components/dynamic/one.vue'
import Two from '../components/dynamic/two.vue'
import Three from '../components/dynamic/three.vue'
export default {
  components: { one, Two, Three },
  data () {
    return {
      // 控制切换按钮后按钮改变样式
      index: 1,
      // 控制子组件显示
      comp: 'one',
      // 控制点击按钮后子组件显示,再次点击隐藏
      isShow: true
    }
  },
  methods: {
    show (value) {
      console.log(value);
      if (this.index === value) {
        this.index = 0
        this.isShow = !this.isShow
      } else {
        this.index = value
        this.isShow = true
      }
      if (value === 1) this.comp = 'one'
      if (value === 2) this.comp = 'two'
      if (value === 3) this.comp = 'three'
    }
  }
}
</script>

<style scoped lang="scss">
.page {
  .button {
    span {
      display: inline-block;
      height: 40px;
      line-height: 40px;
      text-align: center;
      width: 100px;
      border: 1px solid #e6e6e6;
      cursor: pointer;
    }
    .active {
      color: #ffffff;
      background: rgb(49, 49, 238);
    }
  }
}  
</style>

  • 测试效果
posted @ 2021-12-12 13:50  DogLeftover  阅读(109)  评论(0编辑  收藏  举报