Vue2 组件封装

Vue2组件封装精要
本文深入探讨Vue2组件的封装技巧,包括子组件引入、父组件向子组件传值、子组件向父组件传值等核心概念。通过实例演示如何在父组件中注册和使用子组件,以及组件间的数据传递机制。

Vue2 组件封装

1.前言:

接触一个前端框架,除了基础的使用语法以外我们接下来都会很关心组件和复用的问题。以下就是个简单的例子。

2. 子组件引入

下面是在父组件中引入子组件的代码片段:

<template>
<div class="booklist_out_container">
    <div class="booklist_container">
      <BookItem  v-for="book in books" :book="book"/>
    </div>
    <br/>
    <button type="button" @click='onAddBook()' >add book</button>
</div>
</template>

<script>
import BookItem from '@/components/BookItem';
export default {
    mounted() {

    },
    methods: {
      onAddBook:function(){
        this.books = [...this.books,`book${this.books.length}`];
      }
    },
    name: "BookList",
    data() {
        return {
            books:["book0","book1"],
            msg: 'this is BookList',
        };
    },
    components:{
      "BookItem":BookItem
    }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.booklist_out_container{
  width:500px;
  height:400px;
  margin: 0 auto;
}

.booklist_container {
    width: 500px;
    height: 300px;
    border: 1px solid;
    overflow-y:scroll;
}
</style>

从上面的例子可以看出,BookItem既是一个子组件,我们使用:

  • import BookItem from ‘@/components/BookItem’; 方式将子组件引入父组件中。
  • 使用 componets属性,将BookItem组件注册进父组件。
  • 在template标签中使用BookItem子组件。

3. 父组件->子组件传值

使用上面的例子,我们可以看见 :book即是父组件注入到子组件中的一个值,

父组件片段:


    <div class="booklist_container">
      <BookItem  v-for="book in books" :book="book"/>
    </div>

子组件代码:


<template>
<div class="bookitem_container">
    {{book}}<button @click="signUp()">sign up</button>
</div>
</template>

<script>
export default {
    props:{
        book:String,
        required:true
    },
    methods:{
        signUp:function(){
            alert(this.book);
        }
    },
    mounted() {

    },
    name: "BookList",
    data() {
        return {
            msg: 'this is BookList',
        };
    },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.bookitem_container {
    width:100%;
}
</style>


我们可以看见,子组件通过如下方式引入父组件传入的值:

  • props中注册这个值
    props:{
        book:String,
        required:true
    },
  • 在模板中使用:

<template>
<div class="bookitem_container">
    {{book}}<button @click="signUp()">sign up</button>
</div>
</template>

  • 在方法中调用:

    methods:{
        signUp:function(){
            alert(this.book);
        }
    },

4.子组件向父组件传值:

事实上vue2去掉了props的双向绑定,表明了和react一样希望数据流单纯可控,但是实际上我们还是会需要和父组件进行通讯,我们使用$emit方式尽量解耦,方法如下:

将上面的父组件代码修改一下,加入事件监听代码:


<template>
  <div class="booklist_out_container">
      <div class="booklist_container">
        <BookItem  v-for="book in books" :book="book" @:signupEvent="signUpEventListener"/>
      </div>
      <br/>
      <button type="button" @click='onAddBook()' >add book</button>
  </div>
</template>

可以看见关键的代码是:

@:signupEvent="signUpEventListener"
  • @: 表示监听模块。
  • signupEvent 表示监听的事件。
  • signUpEventListener 表示事件处理函数。

子组件增加发送事件代码:


    methods:{
        signUp:function(){
            this.$emit("signupEvent",`something value ${this.book}`);
        }
    },

  • this.$emit 表示发送消息。
  • signupEvent 表示发送一个自定义事件"signupEvent"。
  • something value ${this.book} 表示发送的一个参数。

5.后记

至此,vue2的模块封装相关基础知识已经讲完,高级技巧可以参考官网文档

### 封装常用方法的最佳实践 在 Vue 2封装常用方法可以提高代码的重用性和维护性。通过将重复使用的功能模块化,可以在多个组件之间共享这些工具函数。 #### 创建通用工具库文件 为了便于管理和导入,建议创建一个独立的 JavaScript 文件来保存所有的公用方法。通常命名为 `utils.js` 或者按照功能分类命名,比如 `downloadUtils.js`[^3]。 ```javascript // utils/downloadUtils.js export function downloadLocalFile(file, fileName) { const a = document.createElement('a'); const prefixUrl = process.env.NODE_ENV === 'production' ? '/test/' : '/'; a.href = `${prefixUrl}static/downloadFile/${file}`; a.download = fileName; a.click(); document.body.removeChild(a); } ``` 此段代码展示了如何构建一个简单的文件下载辅助函数,它可以根据环境变量动态调整基础路径,并允许指定要下载的具体文件及其名称。 #### 使用 Vuex Store 和持久化插件 对于状态管理方面,在 Vue 应用程序中推荐使用 Vuex 来集中管理应用的状态逻辑。当涉及到需要跨页面保留的数据时,则可以通过引入第三方库如 `vuex-persistedstate` 来实现数据的本地缓存[^1]。 ```bash npm install store2 vuex-persistedstate --save ``` 接着定义全局可用的状态仓库: ```javascript import Vue from 'vue'; import Vuex from 'vuex'; import createPersistedState from 'vuex-persistedstate'; Vue.use(Vuex); const store = new Vuex.Store({ state: {}, mutations: {}, actions: {}, plugins: [ createPersistedState() ] }); export default store; ``` 这段配置使得任何存储于 Vuex 内部的状态都可以被自动序列化并保存到浏览器会话或本地存储中去,从而实现了简单而有效的持久化机制。 #### Axios 请求拦截器 网络请求也是应用程序开发中的重要部分之一。利用 axios 可以为 HTTP 客户端添加自定义行为,例如统一处理错误响应、附加认证令牌等操作[^4]。 ```javascript // src/utils/request.js import axios from 'axios'; const service = axios.create({ baseURL: '/', timeout: 5000, }); service.interceptors.request.use( config => { // Do something before request is sent return config; }, error => Promise.reject(error), ); service.interceptors.response.use( response => response.data, error => Promise.reject(error), ); export default service; // api/index.js import service from './request'; export function fetchData(params) { return service.get('/api/data', { params }); } export function postData(data) { return service.post('/api/submit', data); } ``` 这里展示的是基于 axios 构建的服务层抽象以及两个具体的 API 方法——获取远程数据(`fetchData`)和提交表单(`postData`)。这样的设计有助于简化业务逻辑层面的操作,同时也方便后续对通信细节做出更改。 #### 组件内部调用 最后一步是在实际的 Vue 组件里边引用之前所准备好的各种实用工具和服务接口。这可以通过 ES6 导入语句轻松完成。 ```html <template> <!-- ... --> </template> <script> import { mapActions } from 'vuex'; import { fetchData, postData } from '@/apis'; import { downloadLocalFile } from '@/utils/downloadUtils'; export default { name: 'ExampleComponent', methods: { ...mapActions(['someAction']), async loadData() { try { const result = await fetchData({ queryParam: value }); console.log(result); } catch (err) { alert(err.message || '加载失败!'); } }, submitForm(formData) { postData(formData).then(() => this.$router.push('/success')); }, triggerDownload(filename) { downloadLocalFile(`${filename}.pdf`, filename); } } }; </script> ``` 以上就是关于如何在 Vue 2 中合理地组织和复用代码的一些指导原则和技术要点。遵循这些做法不仅能够提升项目的整体质量,还能让团队协作更加顺畅高效。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值