Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of extracting mixin by Common method of Vue component

2025-04-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article shares the content of an example analysis of Vue component common method extraction mixin. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.

I. application scenarios

When multiple components share a method, you can use mixin to extract it into a js file as a common method.

II. Method 1. Extract js common method file

export const common = { // 组件共用属性 ---------------------------------- data() { return { age: 18 // 设置一个共用属性 } }, // --------------------------------------------- // 组件共用方法 --------------------------------------------- methods: { showName() { alert(this.name) // 弹出组件中name属性的共用方法 } }, // -------------------------------------------------------- // 组件挂载时的共用方法 ---------------------- mounted() { console.log('初始化方法') // 挂载时调用 }, // ---------------------------------------- }2.引入 组件 弹出姓名 // 引入js文件中的方法对象 -------------------- import {common, } from '../pub_js/common.js' // ---------------------------------------- export default { name: 'Student', data() { return { name: '张三' } }, // 调用 mixin 将组件js与共用js合并 --- mixins: [common, ], // -------------------------------- }三.注意事项

1.data中的属性合并后,如果有命名冲突的情况,以组件中的属性为主,【组件属性覆盖共用js中的属性】

2.methods中的方法合并后,如果有命名冲突的情况,以组件中的方法为主,【组件方法覆盖共用js中的方法】

3.mounted等生命周期方法合并后,会先调用共用js中的的生命周期函数,再调用组件中的生命周期函数,【不会进行覆盖】

4.如果是全局共用的方法,可以直挂载到main.js中↓

import Vue from 'vue'import App from './App.vue'Vue.config.productionTip = false// 挂载全局共用方法 -----------------------import {common, } from 'pub_js/common.js'Vue.mixin(common)// --------------------------------------new Vue({ render: h => h(App),}).$mount('#app')感谢各位的阅读!关于"Vue组件公用方法提取mixin的示例分析"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report