Vue多个单文件组件使用

在project目录下创建components文件夹,然后将所有子组件放入components文件夹下  【创建此目录】【文件名的首字母大写】

1、多组件嵌套使用

Child1.vue

<template>
    <div>子组件1</div>
</template>

<script>
// export default {

// }
</script>

<style>

</style>

Child2.vue

<template>
    <div>子组件2</div>
</template>

<script>
// export default {

// }
</script>

<style>

</style>

App.vue

<template>
    <div>
        单文件组件
        <!-- 调用子组件 -->
        <Child1></Child1>
        <Child2></Child2>
    </div>

</template>


<script>
    //导入components目录下的子文件 Child1为指定的组件名,可以任意命名,不一定按照文件名
import Child1 from './components/Child1.vue'
import Child2 from './components/Child2.vue'

export default {
    // 将子组件添加到App.vue中
    components:{
        Child1,
        Child2,

    }
}
</script>

<style>

</style>

2、多组件路由使用

使用路由形式将多个单文件组件组合在一起

  1. 定义路由目录和路由文件  【直接在可视化界面新建即可】【在根目录下创建文件夹router,在此目录下创建文件router.js】

    mkdir router
    touch router.js
    
  2. 编写路由文件router.js

    1. import Vue from 'vue'
      // 导入路由插件
      import Router from 'vue-router'
      import Child1 from '../components/Child1.vue'
      import Child2 from '../components/Child2.vue'
      // 在vue中使用插件
      Vue.use(Router)
      export default new Router({
          // 定义匹配规则
         routes:[
             {
                 path:'/',  // 匹配根路径/,加载Chiled1中的内容
                 component:Child1
             },
             {
                 path:'/child2',
                 component:Child2
             }
         ]
      })
      
  3.  

  4. 在main.js中使用路由

    1. import Vue from 'vue'
      import App from './App.vue'
      //导入定义好的路由
      import router from './router/router.js'
      
      new Vue({
          el:'#app',
          router,  //使用路由
          render:function(creater){
              return creater(App)
          }
      })
      
  5. 在App.vue中指定路由标签

    1. <template>
          <div>
              单文件组件
               <!-- 记载路由标签 -->
              <router-view></router-view>
          </div>
      
      </template>
      
      <script>
      </script>
      
      <style>
      </style>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值