欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vuecli中的技巧 组件的使用 创建组件 引入组件 注册组件 使用组件

程序员文章站 2022-07-02 15:26:50
...

vuecli中的技巧 组件的使用 创建组件 引入组件 注册组件 使用组件

组件的使用

所有的组件都在components文件夹,根据需求可以在components中新建文件夹

创建组件

在comments上右键,新建文件,起名为组件名.vue

引入组件

在父组件中,引入想要使用的子组件。尽量将起的名字和组件名保持一致

import 组件配置对象名 from 'xxx.vue的路径'

注册组件

在父组件的组件配置对象中,进行组件的注册

export default {
  components: {
    组件名: 组件配置对象名
  }
}

使用组件

注册后的组件会有一个组件标签<组件名>

<template>
  <div>
    <组件名></组件名>
  </div>
</template>

把所有的请求,放在一起

因为,如果不放在一起,我们会将请求分散在不同的Vue组件中,一旦某个请求发生了改变,那么我们不方便维护。放在一起方便维护

src/service/针对当前接口类别的js

// 引入axios
import axios from 'axios'

// 设置接口公共的url
axios.defaults.baseURL = "公共接口前缀"


export const 函数名 = (id) => {
  return axios.get(url, {
    params: {
      // 参数由函数的参数传递
      id
    }
  })
}

// 或者

const 函数名 = () => {}
const 函数名2 = () => {}

export {
  函数名,
  函数名2
}
/* 
  export 的方式导出我们的模块
  在引入时需要使用 import {模块名} from '路径'

*/

写好相关的service之后,我们就可以在需要发起请求的组件中导入对应的函数,进行接口请求。

<template>
</template>
<script>
  import {函数} from 'service路径'

  export default {
    created () {
      函数(参数).then(res => {
        // 处理res中的数据
      })
    }
  }

</script>

bus的使用

在src下新建一个bus.js

import Vue from 'vue'
// export default new Vue()
const bus = new Vue()
export default bus

在需要非父子通信的位置,引入bus并使用即可

import bus from '@/bus'
相关标签: vue