There is an example of chat interface in mui. After upgrading to uni-app, there is no similar template, so I imitated and wrote one. I encountered some pitfalls and recorded them one by one here. Of course, since you are a newbie, there may be some pitfalls that you can avoid.
Preview effect
Setting the scroll-view height
After inputting the content, the content must be displayed at the bottom of the dialog interface. However, I don’t know how to operate the DOM to display and position it under uni-app. It is said that uni.pageScrollTo is needed, but the page refreshes too much. Enter The boxes have been refreshed and cannot be used. So only the scroll-view component can be used. But when using vertical scrolling through scroll-view, you need to give a fixed height. In order to adapt to the size of the screen, the height of the scroll-view needs to be determined through calculation.
<scroll-view id="scrollview" :style="{height:style.contentViewHeight+'px'}" :scroll-with-animation="true" :scroll-top="scrollTop">
</scroll-view>
style.contentViewHeight needs to be calculated before loading
created: function () {
const res = uni.getSystemInfoSync();
this.style.pageHeight = res.windowHeight;
this.style.contentViewHeight = res.windowHeight - uni.getSystemInfoSync().screenWidth / 750 * (100); //像素
}
Since the pixel height is given, you need to convert res.windowHeight - uni.getSystemInfoSync().screenWidth / 750 * (100); where 100 is the pixel height of the bottom input box
Use of scroll-top
Each time the content is sent, it needs to be scrolled to the bottom. This can be achieved by assigning the last element id to scroll-into-view, but the effect is not very satisfactory, so the scroll-top method is used.
var that = this;
var query = uni.createSelectorQuery();
query.selectAll('.m-item').boundingClientRect();
query.select('#scrollview').boundingClientRect();
query.exec(function (res) {
that.style.mitemHeight = 0;
res[0].forEach(function (rect) {
that.style.mitemHeight = that.style.mitemHeight + rect.height + 20;});
if (that.style.mitemHeight > that.style.contentViewHeight) {
that.scrollTop = that.style.mitemHeight - that.style.contentViewHeight;
}
});
The method is to first get the height of all internal sub-elements, and then use the height of the sub-elements and the -display height to get the scroll position of scroll-top.
other
- There is a problem with the address of the img component of uni-app. The applet version can use absolute addresses, but the app version needs to use relative paths.
- Although now you can scroll to the bottom after sending a message, but when typing, the keyboard may pop up and it may be covered, making it impossible to see the last message.
at last
Source code screenshot:
illustrate
If this project is helpful to you, please "like, follow" and support. Thank you~
To get the source code, follow the public account "Coder Park" and reply [uniapp source code]