vue全局引用公共的组件以及公共的JS文件问题

Jacinda ·
更新时间:2024-09-20
· 364 次阅读

目录

全局引用公共的组件及公共的JS文件

全局引入自定义组件问题

全局引用公共的组件及公共的JS文件

1. 创建一个公共的目录 timeline ,里面包含 timeline.js 和 timeline.vue 文件,timeline.vue 用来写公共的页面,timeline.js 用来导出这个组件。

timeline.vue 文件内容如下

<template> <div>页面展示内容</div> </template> <script> export default { data() { return {}; }, methods: {} }; </script> <style lang="less" scoped> </style>

timeline.js 文件内容如下

import timelineData from './timeline.vue'; const timeline = { install: (Vue) => { // 注册并获取组件,然后在 main.js 中引入,并 Vue.use()挂载 Vue.component('timeline', timelineData) } }; export default timeline;

2. 在 main.js 中引入公共的文件并挂载到Vue中

... // 引入timeline import timeline from './timeline/timeline.js'; Vue.use(timeline); ...

3. 在需要用到 timeline 的组件文件中直接使用即可

<template> <div> // 页面中直接使用即可 <timeline></timeline> </div> </template> 全局引入自定义组件问题

1. 书写组件

<!-- index.vue --> <template> <button class="h-button" :type="type"> <slot></slot> </button> </template> <script> export default { props:{ type:{ type:String, default:'button' } }, data(){ return{ } } } </script>

2. 暴露install()方法

// index.js import HButton from './index.vue'; HButton.install=function(Vue){ Vue.component('HButton',HButton) // (组件名称,对应组件) } export default HButton;

3. 全局注册

// main.js // @ is an alias to /src import HButton from '@/components/Btn/index' Vue.use(HButton)

4. 使用

<!-- Home.vue 使用 --> <template> <div class="home"> <h-button>组件使用</h-button> </div> </template> <script> export default { name: "Home", components: {}, }; </script>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。



VUE js文件 js

需要 登录 后方可回复, 如果你还没有账号请 注册新账号