uniapp JS文件里面调用自定义组件(不用每个页面在template中加组件标签) | 您所在的位置:网站首页 › uniapp自定义模板 › uniapp JS文件里面调用自定义组件(不用每个页面在template中加组件标签) |
前言 工具:uniapp ( Vue2 ) 开发端:微信小程序 其他:uview 2.0 场景:路由器里面,统一验证是否已登录,如果没登录,则直接弹出登录弹窗出来,不管哪个页面都如此。 效果如下: 直接上代码: 第一步:组件封装 components目录下-新建文件-authorized.vue (平常怎么封装的组件就怎么封装 建议把组件放到components目录下面) 需要的自己拿去改 登录体验更多功能 微信一键登录 微信一键登录 《用户协议》 和 《隐私协议》 export default { name:'authorized', data() { return { showAuth: false, checkValueWx: false, }; }, methods: { open() { this.showAuth = true }, checkboxChangeWx(e) { this.checkValueWx = e; }, goLoginWx() { uni.$u.toast('请先阅读并同意用户协议和隐私协议'); }, // 微信授权登录 getPhoneNumber(e) { //登录逻辑操作 }, } } .contactUsDiv { position: relative; background-color: #fff; border-top-left-radius: 15rpx; border-top-right-radius: 15rpx; } .title { position: relative; @include flex; align-items: center; justify-content: center; padding: 50rpx 0; font-size: 17px; .closeIcon { position: absolute; right: 5%; top: 25rpx; font-size: 18px; } } .wxBtn { @include flex; justify-content: center; align-items: center; width: 80%; border-radius: 30rpx; background-color: #ACABAA; font-size: 15px; margin:0 auto; margin-bottom:50rpx; color: #fff; background-color: #00E71F; text { margin-left: 20rpx; } } .xieyi { @include flex; align-items: center; justify-content: center; margin-bottom:100rpx; font-size: 14px !important; .xieyiP { margin-left: 10rpx; color: '#FF8A00'; } }第二步: 项目根目录下新建vue.config.js文件(如果有则跳过) vue.config.js文件中配置代码如下: module.exports = { chainWebpack: config => { config.module.rule('vue').use('vue-loader').loader('vue-loader').tap(options => { const compile = options.compiler.compile options.compiler.compile = (template, ...args) => { // **注意 页面路径请根据自己小程序实际项目结构更改** //args[0].resourcePath.match(/^pages/) **文件路径** //args[0].resourcePath.match(/^pages/)||args[0].resourcePath.match(/^分包文件名\/pages/) **分包路径** if (args[0].resourcePath.match(/^pages/)) { template = ` ${template} `; } return compile(template, ...args) } return options }) } }第三步: 将创建的authorized组件 全局注册 这一步至关重要 main.js文件中加入如下代码: import authorized from “@/components/authorized.vue” Vue.component(‘authorized’,authorized) 以上步骤操作完成,启动项目你就能看见每访问一个页面都加自己加上了组件标签 如下图: 第四步:调用组件-----在Js中调用 可以通过获取页面栈来调用 代码如下: // pages[pages.length-1]-----当前页面路由 let pages = getCurrentPages(); let currentPage = pages[pages.length-1] currentPage. v m . vm. vm.refs.uAuthorized.open() 完整撒花 !(可能纯在的问题: 博主只测试了 小程序没问题,app可能不支持Vue.component这个api小伙伴们可以尝试使用Vue.extend去实现app端的全局挂载,其他的步骤一样) |
CopyRight 2018-2019 实验室设备网 版权所有 |