uniapp使用nvue总结

使用场景1

地图组件、视频组件层级太高,其他组件不能显示在地图或视频组件上方

使用场景2

用到uniapp的瀑布流组件<waterfall>

使用场景3

在地图中,当前位置的marker箭头随手机方向旋转

踩坑:

1、nvue不能使用百分比布局,不能用scss、less,单位不嫩用vw、vh

2、flex布局flex-driection默认是column

3、文字不能使用text-overflow设置显示多行超出部分省略号显示(解决方法在下面)

4、文字的样式只能在<text>才能生效

5、封装好的网络请求在nvue文件中需要重新引入,在main.js里面注册好的网络请求、全局组件、全局filter等都不能直接使用,需要重新引入

瀑布流布局的使用

链接地址:waterfall | uni-app官网

1、<waterfall> 组件的子组件只能包括以下四种组件或是 fix 定位的组件,其他形式的组件将不能被正确渲染

  • <cell>:用于定义列表中的子列表项,类似于 HTML 中的 ul 之于 li。<waterfall> 会对 <cell> 进行高效的内存回收以达到更好的性能。

  • <header>:当 <header> 到达屏幕顶部时,吸附在屏幕顶部。

  • <refresh>:用于给列表添加下拉刷新的功能。

  • <loading><loading> 用法与特性和 <refresh> 类似,用于给列表添加上拉加载更多的功能。

2、属性

  • show-scrollbar : [可选] 可选值为 true/ false,默认值为 true。控制是否出现滚动条。

  • column-count: [可选]描述瀑布流的列数

    • auto: 意味着列数是被其他属性所决定的(比如 column-width)

    • <integer>: 最佳列数,column-width 和 column-count 都指定非0值, 则 column-count 代表最大列数。

  • column-width : [可选]描述瀑布流每一列的列宽

    • auto: 意味着列宽是被其他属性所决定的(比如 column-count)

    • <length>: 最佳列宽,实际的列宽可能会更宽(需要填充剩余的空间), 或者更窄(如果剩余空间比列宽还要小)。 该值必须大于0

  • column-gap: [可选]列与列的间隙. 如果指定了 normal ,则对应 32.

  • left-gap: [可选]左边cell和列表的间隙. 如果未指定 ,则对应 0

 

3、事件

  • appear:用于监听子组件出现事件(一般绑定于子组件之上例如:监听最后一个元素出现,加载新的数据)

<waterfall column-count="2" left-gap="10" column-gap="10" right-gap="10"
		:style=" 'height: '+windowHeight + 'px;padding-bottom:160rpx;' ">
		<header style="position: sticky;top: 0;background-color: #fff;">
			<view class="headfix" :style="'padding-top:'+statusbarH+'px'">
				<image class="bg" src="../../static/index/groupbg.png" mode="widthFix" style="width: 750rpx"></image>
				<view class="head">
					<image src="../../static/icon/grouplogo.png" mode="widthFix"
						style="width: 90rpx;margin-right: 20rpx;margin-bottom: 4rpx;"></image>
					<view class="tab">
						<view :class="['tab-item',current==0?'active':'']" @click="current=0">
							<view class="line"></view>
							<text class="text">推荐</text>
						</view>
						<view :class="['tab-item',current==1?'active':'']" @click="current=1">
							<view class="line"></view>
							<text class="text">{{city}}</text>
						</view>
					</view>
					<image src="../../static/icon/jf.png" mode="widthFix" style="width: 136rpx;" @click="goscore">
					</image>
				</view>
			</view>
			<view class="searchbox">
				<view class="search">
					<u-icon name="search" size="24" color="#999"></u-icon>
					<input class="ipt" type="text" placeholder="请输入关键词" v-model="keywords" />
					<view class="btn">
						<u-icon name="search" color="#fff" size="24" @click="reload"></u-icon>
					</view>
				</view>
			</view>

			<scroll-view scroll-x="true" :show-scrollbar="false"
				style="width: 750rpx;white-space: nowrap;height: 100rpx;display: flex;flex-direction: row;">
				<view class="tabs_box">
					<view :class="currenttab==-1?'tabs_item':'tabs_items'" @click="changetab(-1)"><text
							class="tabtext">全部资讯</text>
					</view>
					<view :class="currenttab==0?'tabs_item':'tabs_items'" @click="changetab(0)"><text
							class="tabtext">最新发布</text>
					</view>

					<view :class="item.id==currenttab?'tabs_item':'tabs_items'" v-for="(item,index) in cate"
						:key="index" @click="changetab(item.id)">
						<text class="tabtext">{{item.label}}</text>
					</view>

				</view>
			</scroll-view>
			<view class="" v-if="infolist.length==0"
				style="width: 750rpx;display: flex;justify-content: center;flex-direction: row;">
				<image src="/static/index/empty.png" mode="widthFix"
					style="width: 500rpx;display: block;margin: 100rpx auto;"></image>
			</view>
		</header>
		<cell v-for="(item, index) in infolist" :key="index" @appear="more(index)">

			<view class="list-item" @click="godetail(item.id)">
				<image :src="tool.cdn(tool.split(item.uploadedimages)[0])"
					style="width: 100%;height: 320rpx; border-radius: 20rpx 20rpx 0 0;" class="cover" mode="widthFix">
				</image>

				<view class="title">
					<rich-text class="titletext" :nodes="getRichText(item.detail)"></rich-text>
				</view>
				<view class="info">
					<image
						:src="item.avatar?tool.cdn(item.avatar):config.head_image?tool.cdn(config.head_image):'/static/index/default.png'"
						class="avatar" mode="aspectFill">
					</image>
					<view class="mid">
						<rich-text class="name" :nodes="getRichText(item.nickname)"></rich-text>
						<text class="time">{{item.time | formatTime}}</text>
					</view>
					<view class="right">
						<u-icon name="eye" color="#999"></u-icon>
						<text class="righttext">{{tool.formatViews(item.page_views)}}次浏览</text>
					</view>
				</view>
			</view>
		</cell>
		<view class="tabbar">
			<view class="tabbar-item" v-for="(item,index) in tabbar" :key="index" @click="go(item)">
				<image :class="['tabicon',item.nav==2?'midbtn':'']" :src="item.selectedIconPath" mode="aspectFill"
					v-if="1==index"></image>
				<image :class="['tabicon',item.nav==2?'midbtn':'']" :src="item.iconPath" mode="aspectFill" v-else>
				</image>
				<text :class="['text',1==index?'tabactive':'']" v-if="item.text">{{item.text}}</text>
			</view>
		</view>
	</waterfall>
.list-item {
		border-radius: 20rpx;
		overflow: hidden;
		background-color: #fff;
		margin-bottom: 20rpx;
	}

	.list-item .title {
		/* height: 50px; */
		/* width: 300rpx; */
		/* padding: 0 10rpx; */
		box-sizing: border-box;
	}

	.list-item .titletext {
		font-size: 28rpx;
		color: #333;
		line-height: 40rpx;
		lines: 2;
		text-overflow: ellipsis;
	}

	.list-item .info {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.list-item .info .avatar {
		width: 56rpx;
		height: 56rpx;
		border-radius: 30rpx;
		margin-right: 10rpx;
	}

	.list-item .info .mid {
		width: 150rpx;
		display: flex;
		flex-direction: column;
	}

	.list-item .info .mid .name {
		color: #999;
		font-size: 24rpx;
		line-height: 32rpx;
		lines: 1;
		text-overflow: ellipsis;
	}

	.list-item .info .mid .time {
		color: #999;
		font-size: 24rpx;
	}

	.list-item .info .right {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.list-item .info .right .righttext {
		color: #999;
		font-size: 24rpx;
	}

	.tabbar {
		display: flex;
		align-items: center;
		flex-direction: row;
		justify-content: space-around;
		background-color: #fff;
		padding: 20rpx 20rpx 40rpx;
		box-sizing: border-box;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 750rpx;
		border-top: 1rpx solid #eee;

	}

	.tabbar .tabbar-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		flex: 1;

	}

	.tabbar .tabbar-item .tabicon {
		width: 48rpx;
		height: 48rpx;
		margin-bottom: 10rpx;
	}

	.tabbar .tabbar-item .text {
		font-size: 24rpx;
		line-height: 40rpx;
		color: #3d3d3d;
	}

	.tabbar .tabbar-item .text.tabactive {
		color: #3792FF;
	}

	.tabbar .tabbar-item .midbtn {
		width: 96rpx;
		height: 60rpx;
	}
import HTMLParser from '@/utils/html-parser'

// nvue不支持直接传字符串
getRichText(content) {
	this.content = new HTMLParser(content.trim())
	return this.content
},
//监听最后一个元素 加载新数据
more(index) {
	if (this.infolist.length - 1 == index) {
		this.page++
		this.getInfolist();//加载数据
	}
},

效果图

文字显示x行,超出部分省略号显示

参考链接:https://juejin.cn/post/7149110487014178824

uniapp中的nvue页面文本必须放在text标签里面,否则不能设置字体大小和颜色,且只能显示一行,如果想显示多行,则需要使用rich-text标签

text和rich-text如果需要显示省略号,可以使用lines和text-overflow属性

html-parser.js 文件

/*
 * HTML5 Parser By Sam Blowes
 *
 * Designed for HTML5 documents
 *
 * Original code by John Resig (ejohn.org)
 * http://ejohn.org/blog/pure-javascript-html-parser/
 * Original code by Erik Arvidsson, Mozilla Public License
 * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
 *
 * ----------------------------------------------------------------------------
 * License
 * ----------------------------------------------------------------------------
 *
 * This code is triple licensed using Apache Software License 2.0,
 * Mozilla Public License or GNU Public License
 *
 * 
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.  You may obtain a copy
 * of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * 
 *
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * The Original Code is Simple HTML Parser.
 *
 * The Initial Developer of the Original Code is Erik Arvidsson.
 * Portions created by Erik Arvidssson are Copyright (C) 2004. All Rights
 * Reserved.
 *
 * 
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * ----------------------------------------------------------------------------
 * Usage
 * ----------------------------------------------------------------------------
 *
 * // Use like so:
 * HTMLParser(htmlString, {
 *     start: function(tag, attrs, unary) {},
 *     end: function(tag) {},
 *     chars: function(text) {},
 *     comment: function(text) {}
 * });
 *
 * // or to get an XML string:
 * HTMLtoXML(htmlString);
 *
 * // or to get an XML DOM Document
 * HTMLtoDOM(htmlString);
 *
 * // or to inject into an existing document/DOM node
 * HTMLtoDOM(htmlString, document);
 * HTMLtoDOM(htmlString, document.body);
 *
 */
// Regular Expressions for parsing tags and attributes
var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
var attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; // Empty Elements - HTML 5

var empty = makeMap('area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr'); // Block Elements - HTML 5
// fixed by xxx 将 ins 标签从块级名单中移除

var block = makeMap('a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video'); // Inline Elements - HTML 5

var inline = makeMap('abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'); // Elements that you can, intentionally, leave open
// (and which close themselves)

var closeSelf = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'); // Attributes that have their values filled in disabled="disabled"

var fillAttrs = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'); // Special Elements (can contain anything)

var special = makeMap('script,style');
function HTMLParser(html, handler) {
  var index;
  var chars;
  var match;
  var stack = [];
  var last = html;

  stack.last = function () {
    return this[this.length - 1];
  };

  while (html) {
    chars = true; // Make sure we're not in a script or style element

    if (!stack.last() || !special[stack.last()]) {
      // Comment
      if (html.indexOf('<!--') == 0) {
        index = html.indexOf('-->');

        if (index >= 0) {
          if (handler.comment) {
            handler.comment(html.substring(4, index));
          }

          html = html.substring(index + 3);
          chars = false;
        } // end tag

      } else if (html.indexOf('</') == 0) {
        match = html.match(endTag);

        if (match) {
          html = html.substring(match[0].length);
          match[0].replace(endTag, parseEndTag);
          chars = false;
        } // start tag

      } else if (html.indexOf('<') == 0) {
        match = html.match(startTag);

        if (match) {
          html = html.substring(match[0].length);
          match[0].replace(startTag, parseStartTag);
          chars = false;
        }
      }

      if (chars) {
        index = html.indexOf('<');
        var text = index < 0 ? html : html.substring(0, index);
        html = index < 0 ? '' : html.substring(index);

        if (handler.chars) {
          handler.chars(text);
        }
      }
    } else {
      html = html.replace(new RegExp('([\\s\\S]*?)<\/' + stack.last() + '[^>]*>'), function (all, text) {
        text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, '$1$2');

        if (handler.chars) {
          handler.chars(text);
        }

        return '';
      });
      parseEndTag('', stack.last());
    }

    if (html == last) {
      throw 'Parse Error: ' + html;
    }

    last = html;
  } // Clean up any remaining tags


  parseEndTag();

  function parseStartTag(tag, tagName, rest, unary) {
    tagName = tagName.toLowerCase();

    if (block[tagName]) {
      while (stack.last() && inline[stack.last()]) {
        parseEndTag('', stack.last());
      }
    }

    if (closeSelf[tagName] && stack.last() == tagName) {
      parseEndTag('', tagName);
    }

    unary = empty[tagName] || !!unary;

    if (!unary) {
      stack.push(tagName);
    }

    if (handler.start) {
      var attrs = [];
      rest.replace(attr, function (match, name) {
        var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : '';
        attrs.push({
          name: name,
          value: value,
          escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') // "

        });
      });

      if (handler.start) {
        handler.start(tagName, attrs, unary);
      }
    }
  }

  function parseEndTag(tag, tagName) {
    // If no tag name is provided, clean shop
    if (!tagName) {
      var pos = 0;
    } // Find the closest opened tag of the same type
    else {
        for (var pos = stack.length - 1; pos >= 0; pos--) {
          if (stack[pos] == tagName) {
            break;
          }
        }
      }

    if (pos >= 0) {
      // Close all the open elements, up the stack
      for (var i = stack.length - 1; i >= pos; i--) {
        if (handler.end) {
          handler.end(stack[i]);
        }
      } // Remove the open elements from the stack


      stack.length = pos;
    }
  }
}

function makeMap(str) {
  var obj = {};
  var items = str.split(',');

  for (var i = 0; i < items.length; i++) {
    obj[items[i]] = true;
  }

  return obj;
}

function removeDOCTYPE(html) {
  return html.replace(/<\?xml.*\?>\n/, '').replace(/<!doctype.*>\n/, '').replace(/<!DOCTYPE.*>\n/, '');
}

function parseAttrs(attrs) {
  return attrs.reduce(function (pre, attr) {
    var value = attr.value;
    var name = attr.name;

    if (pre[name]) {
			pre[name] = pre[name] + " " + value;
    } else {
			pre[name] = value;
    }

    return pre;
  }, {});
}

function parseHtml(html) {
  html = removeDOCTYPE(html);
  var stacks = [];
  var results = {
    node: 'root',
    children: []
  };
  HTMLParser(html, {
    start: function start(tag, attrs, unary) {
      var node = {
        name: tag
      };

      if (attrs.length !== 0) {
        node.attrs = parseAttrs(attrs);
      }

      if (unary) {
        var parent = stacks[0] || results;

        if (!parent.children) {
          parent.children = [];
        }

        parent.children.push(node);
      } else {
        stacks.unshift(node);
      }
    },
    end: function end(tag) {
      var node = stacks.shift();
      if (node.name !== tag) console.error('invalid state: mismatch end tag');

      if (stacks.length === 0) {
        results.children.push(node);
      } else {
        var parent = stacks[0];

        if (!parent.children) {
          parent.children = [];
        }

        parent.children.push(node);
      }
    },
    chars: function chars(text) {
      var node = {
        type: 'text',
        text: text
      };

      if (stacks.length === 0) {
        results.children.push(node);
      } else {
        var parent = stacks[0];

        if (!parent.children) {
          parent.children = [];
        }

        parent.children.push(node);
      }
    },
    comment: function comment(text) {
      var node = {
        node: 'comment',
        text: text
      };
      var parent = stacks[0];

      if (!parent.children) {
        parent.children = [];
      }

      parent.children.push(node);
    }
  });
  return results.children;
}

export default parseHtml;

引入html-parser.js文件

<rich-text class="name" :nodes="getRichText(item.nickname)"></rich-text>

.name {
	color: #999;
	font-size: 24rpx;
	line-height: 32rpx;
	lines: 2;//显示几行
	text-overflow: ellipsis;
}

import HTMLParser from '@/utils/html-parser'
// nvue不支持直接传字符串 将字符串转化为富文本
getRichText(content) {
	this.content = new HTMLParser(content.trim())
	return this.content
},

在地图上,当前位置marker箭头随手机方向旋转

<map name="" id="map" :scale="12" :latitude="latitude" :longitude="longitude" :markers="covers" :polyline="polyline" ></map>

//js
export default {
    data(){
        return {
            latitude: '',
			longitude: '',
            polyline: [],
            rotate:0,//旋转角度
        }

    },
    computed: {
			covers() {
				return [{
					id: 1,
					latitude: this.latitude,
					longitude: this.longitude,
					iconPath: '../../static/now2.png',
					title: '当前位置',
					width: 25,
					height: 25,
					rotate: this.rotate
				}]
			},
	},
    onLoad(option) {
			uni.onCompassChange(res => {
				// 计算旋转角度,根据实际需求调整
				this.rotate = res.direction;
				// console.log('旋转角度',res.direction)
			});
		},
    

}

成长中...

有错误的地方请您指正,有更好的建议欢迎评论

uniApp采用NVue(基于Vue.js的框架)进行开发,Live-Pusher是一种用于直播推流的技术。当在uniApp中集成NVue并尝试使用Live-Pusher进行横屏直播时,如果遇到屏幕旋转90度的问题,这通常是因为页面的布局和媒体流的方向没有很好地适应设备方向变化。 原生的WebRTC API可能会在横竖屏切换时出现问题,因为直播组件需要保持与视频流一致的方向。解决这个问题通常需要以下几个步骤: 1. **设置viewport**: 确保在`<meta>`标签中设置了响应式视口,以便在横屏模式下自动调整。 ```html <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, minimum-scale=1, maximum-scale=1"> ``` 2. **方向检测**: 使用uni-app提供的`uni.getSystemInfo()`方法检查设备方向,并动态改变直播组件的样式或布局。例如,在`mounted`生命周期钩子里监听设备方向改变事件: ```javascript uni.onWindowMessage('onSysInfoChange', (event) => { if (event.systemInfo.orientation === 'landscape') { // 横屏处理代码 } else { // 竖屏处理代码 } }) ``` 3. **CSS媒介查询**: 使用CSS的`@media screen and (orientation: landscape)`来针对横屏环境应用特殊的CSS规则,让直播组件能够正确显示。 4. **自适应组件**: 如果Live-Pusher本身支持横屏模式,确保在开发者文档中查找是否有相应的配置选项或API来启用横屏适配。 5. **兼容性处理**: 对于一些老旧浏览器,可能需要手动处理触摸缩放和旋转事件,保证直播体验的一致性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值