Vue多个单文件组件使用
  TEZNKK3IfmPf 2023年11月14日 24 0

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

Vue多个单文件组件使用

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. Vue多个单文件组件使用 Vue多个单文件组件使用

  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>
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年04月26日   34   0   0 htmlScala
TEZNKK3IfmPf