In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to encapsulate query components based on element-ui. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
Function
Then the previous article encapsulated a better table component based on the element-ui framework, and we began to write query components. What do you need to query the component? Here I draw a rough prototype that basically describes the functions that the query component needs to implement.
Basic query function [enter conditions, select drop-down data and click to query]
Add query drop-down panel [for many queries, one line cannot be put down, you need to give more query drop-down panels. Get rid of the default query conditions, put down the ramen board, and put several specific default query conditions, which can be controlled by the passed parameters]
Add condition display [if there are more query panels, if you do not open the query panel, it is not clear on which conditions the data is checked.]
Add function button area [generally place function buttons for batch operations such as addition, deletion, modification, etc.]
Basic query function
Query function, need to match element-ui input box, drop-down box, date box and other components to achieve, and with our components, we want to use an array to describe the query conditions, and then components according to the array to identify and render the conditions. First, we have to define what the array looks like.
/ methodsinitSearch () {const searchArr = this.searchArr if (searchArr & & searchArr.length) {let searchForm = {} searchArr.forEach ((val) = > {searchForm [val.key] =''}) this.searchForm = searchForm}} / / mountedmounted () {this.initSearch ()}
At present, these three fields are the most basic, and the meaning of the field has been clearly written in the code comments. Some other fields may be extended in this object. For example, drop-down data is usually sent to the front end through the background interface. Here, we can add a url, param, method to define the name, parameters and request method of the interface. Of course, when it is realized later, we will talk about it. So let's start developing.
Query condition initialization
After we pass in the searchArr data, we have to traverse it in mounted and set the responsive data to the query condition searchForm defined by the content.
/ / methodsinitSearch () {const searchArr = this.searchArr if (searchArr & & searchArr.length) {let searchForm = {} searchArr.forEach ((val) = > {searchForm [val.key] =''}) this.searchForm = searchForm}} / / mountedmounted () {this.initSearch ()}, render the page
Because the query page we designed is two-part, including the query conditions displayed outside and the query conditions displayed in more query conditions. In this way, if we define the structure in template, we will find that we need to write repetitive code twice. If the new functions are expanded in the back, it will be another uncomfortable physical job. So we write jsx in the render function, which makes the structure more flexible and the code can be better reused. When the train of thought is over, then start writing the code.
/ / props pass in an searchArr array to describe the query conditions / * query condition description * / searchArr: {type: Array, default: () = > []}, / / data defines two variables, and searchForm: the query field passed to the background SelectOption: drop-down data searchForm: {}, selectOption: {} / / mounted initialization data initSearch () {const searchArr = this.searchArr if (searchArr & & searchArr.length) {let searchForm = {} searchArr.forEach ((val) = > {searchForm [Val. _ _ key] =''/ / take out the user-defined fields and put them in searchForm Then assign an empty string this.setOption (val) / / if it is drop-down data To assign the drop-down list to selectOption}) this.searchForm = searchForm}}, / / methods sets the drop-down data async setOption (val) {if (~ ['select',' mulSelect'] .indexOf (val.__type)) {/ / the first case if the drop-down data is locally written if (val.data & & Array.isArray (val.data)) {this.$set (this.selectOption, val.__key) Val.data)} else if (val.fetchUrl) {/ / the second case If the drop-down data is the data passed from the background interface const result = await request ({url: val.fetchUrl, method: val.method | | 'post'}) if (result & & result.data & & result.data.success) {this.$set (this.selectOption, val.__key, result.data.list | | [])}
OK, after we have finished the initialization work, we can do the rendering work. As we said earlier, it would be more flexible to write jsx in the render function, so let's start writing this part of the work.
/ / render function {searchArr.map ((o) = > {return statements [o. _ type]? Queries [o. _ _ type] (h, o, this):''})} query {this.moreShow =! this.moreShow}} > more queries / /. More queries
It is worth noting that in the latest vue-cli, the use of instructions such as v-model in jsx is already supported, but the use of el-input in element-ui will report an error, and the v-show instruction used below can be used. But in fact, v-model is just a syntax candy. Here we use the input event to get the latest input data, and then assign it to searchForm. This code is extracted because it is used for both externally displayed query conditions and shrinking query conditions, and after extraction, there is no need to write repetitive logic. Here are the extracted components components
/ * Why is the input box removed? Here we just need to do a table query. * in fact, if you want to encapsulate a form submission component like a pop-up window frame. You can also reuse the h function provided by the logic * @ param {Function} h vue * @ param {Object} item user written description object * @ param {Object} vm vue instance * / export const input = function (h, item) Vm) {const {searchForm} = vm return ({searchForm [item. _ _ key] = v}} props= {{value: searchForm [item. _ _ key], placeholder: "enter content information" . item}} >)} / * @ h vue provided by param {Function} h function * @ param {Object} item user written description object * @ param {Object} vm vue instance * / export const select = function (h, item, vm) {const {searchForm = {}, selectOption = {} } = vm / * listen for drop-down change event * @ param {String | Number | Boolean} value Select the value of drop-down data * @ param {Object} value * / const selectChange = function (value, item) {searchForm [item. _ _ key] = value vm.$emit ('on-change', value)} return ({selectChange (val) Item)}} size= "small" > {return option [item. _ _ key] & & select option [item. _ _ key] .map ((o) = > {option ()})) } / multiple selection drop-down box Can add two attributes on the basis of single selection, write one of this method, the user can have a few fewer words. * @ param {Function} h vue provided h function * @ param {Object} item user written description object * @ param {Object} vm vue instance * / export const mulSelect = function (h, item, vm) {item ['multiple'] = true item [' collapse-tags'] = true return select (h, item, vm)}
In fact, the above is to extract several components of element into independent methods. When we use external components, we can directly match the type passed by users to the corresponding components to render. And if you want to add a new query component later, just expand it here and you don't have to modify it anywhere else. Easier to maintain. In addition, we default some behaviors within the component, such as the default drop-down can be searched, the default has a clear button, etc., if the system does not need it, you can also write the corresponding attribute override in searchArr.
Return components[o. _ _ type]? Statements [o. _ _ type] (h, o, this):''
The basic rendering is done, and then we use the components outside.
SearchArr: [{_ _ type: 'input', label:' name', _ _ key: 'name'}, {_ _ type:' select', label: 'gender', _ _ key: 'sex', fetchUrl:' / getSelect', method: 'post' / / data: [/ / {text:' male' Value:'1'}, / / {text: 'female', value:'0'}, / /]
Write down the corresponding mock data
Mock.mock (/\ / getSelect/, 'post', () = > {return {status: 200, success: true, message:' get success', list: [{text: 'man', value:'1'}, {text: 'woman, value:' 2'}], total: data.list.length}})
Ok, the above simply renders the conditions in the way of array description. Next, we have to do more query conditions for the query panel.
More queries and display optimization
How many query conditions are displayed outside according to the number given by the user, and more queries can also show how many per row according to the parameters given by the user?
= props = / * external query conditions display * / frontCount: {type: Number, default: 2}, / * more query conditions display * / backCount: {type: Number, default: 3} = end props = = computed = / / query conditions displayed on the page frontSearchArr: function () {return this.searchArr.slice (0, this.frontCount)} / / the condition backSearchArr: function () {return this.searchArr.slice (this.frontCount, this.searchArr.length)} shown in more queries / / return width getSpan: function () {const yu = this.backSearchArr.length% this.backCount / / remainder const duan = 24 / this.backCount / / width of each condition if (yu = 0) {return 24} else {return 24-duan}} = end computed = = render = {backSearchArr.map (o) = > {return ({conditions [o. _ type]? Contacts [o. _ _ type] (h, o, this):''})} query {this.moreShow =! this.moreShow}} > shrink = end render =
Set the externally displayed data and internally displayed data in the calculation properties. Cut the data into two parts. Search component fixed length 265. Then calculate the width of more query panels according to the conditions, and then calculate the span width of each row of data according to the getSpan calculation attribute. The query and shrink buttons calculate where it is placed according to the number of query conditions.
After testing, the effect basically meets the requirements.
Pull-down component linkage query
For example, if we need to write a three-level linkage with our query component, how should it be implemented?
After selecting a province, you need to load the corresponding city drop-down data according to the selected province.
If you delete the province, you need to empty the drop-down of the corresponding province and city.
The main purpose of linkage is to do these two functions well. One is to load the corresponding data, and the other is to empty the corresponding data. Ok, now that we know what needs to be done, let's start doing it.
{_ _ type: 'select', _ _ key:' province', _ _ fetchUrl:'/ getProvince', _ _ method: 'get', _ _ nextKey:' city', _ _ nextFetch:'/ getCity', _ _ nextParam: ['province'], _ _ nextMethod:' get', _ _ emptyArr: ['city',' district'], label: 'province', labelWidth: '40pxprovince,}, {_ type:' select' _ _ key: 'city', _ _ method:' get', _ _ nextKey: 'district', _ _ nextFetch:' / getDistrict', _ nextParam: ['province',' city'], _ _ nextMethod: 'get', _ _ emptyArr: [' district'], label: 'city', labelWidth: '40pxcities,}, {_ type:' select', _ key: 'district', label:' area' LabelWidth: '40pxrabbit,}
To obtain the provincial data, you only need to write _ _ fetchUrl:'/ getProvince' and _ _ method: 'get' to define the request API to get the drop-down data. Then when you choose the save drop-down, you need to request data according to the selected province in the change event. At this point, we need to define what needs to be done when change is in the data. Take a look at the code:
_ _ nextKey: 'city', / / which drop-down data is assigned _ _ nextFetch:' / getCity', / / request API _ _ nextParam: ['province'], / / request parameter _ _ nextMethod:' get', / / request method _ _ emptyArr: ['city' 'district'] / / when the drop-down data is modified Which drop-down categories need to clear the value / * listen for drop-down change event * @ param {String | Number | Boolean} value Select the value of drop-down data * @ param {Object} value * / const selectChange = async function (value, item) {searchForm [item. _ _ key] = value / / empty drop-down list and drop-down data if (item & & item.__emptyArr) {for (let I = 0) I
< item.__emptyArr.length; i++) { let key = item.__emptyArr[i] if (selectOption[key]) { selectOption[key] = [] } vm.$set(searchForm, key, '') } } if (item && item.__nextFetch && item.__nextParam) { let param = {} for (let j = 0; j < item.__nextParam.length; j++) { let value = searchForm[item.__nextParam[j]] if (value) { param[item.__nextParam[j]] = value } } const res = await request({ url: item.__nextFetch, method: item.__nextMethod || 'post' }, param) if (res) { let { data } = res if (data && data.success) { vm.$set(selectOption, item.__nextKey, data.list) } } } vm.$emit('on-change', value)} ok, 这样基本就完成了三级联动的功能了。 以下是效果图Component extension
Component extension is very simple. If we still lack some required components, we can add a new one directly in components.js.
/ * date selector * @ param {*} h * @ param {*} item * @ param {*} vm * / export const date = function (h, item, vm) {const {searchForm} = vm return ({type: 'date', size:' small', value: searchform [item. _ _ key]) Placeholder: "Select date",... item}} >)} / / add {_ _ type: 'date', _ _ key:' birthday', label: 'birthday'} when searchArr is used
The addition of a new query condition type is completed without modification elsewhere. Here is the effect
Display of search criteria
The search criteria function is relatively simple, that is, after the user clicks on the search, the input conditions are displayed. Let's separate this as a separate widget.
This component was passed into the drop-down array, and when we designed it, we said that it could also click on the fork to delete the condition, so we had to throw a remove custom event, and then after deleting the condition, we cleared the condition and called the query method. When querying, pass the search criteria to the component and let the component display it. It should be noted here that we cannot directly pass the search criteria into the component through props. If so, because the data is responsive, it will be displayed below when you enter the conditions. This is not the effect we want. What we want is to show the query conditions being queried when the query button is clicked. So here, in the query button method, we directly call its internal method to pass in the conditions, and then use JSON.parse (JSON.stringify (val)) internally to achieve a deep copy to separate the data from the external data.
RemoveTag (name) {this.searchForm [name] =''this.queryTable ()} / / query queryTable () {this.$refs.queryInfo & & this.$refs.queryInfo.queryTable (this.searchForm) this.moreShow = false this.$emit (' search', this.searchForm)}
The components are implemented as follows:
{{displayName (tag)}} import {getTitle} from'@ / utils/utils'export default {props: {/ / drop-down data selectionOption: {type: Object, default: () = > []}}, data () {return {/ / query condition searchForm: {} Computed: {/ calculate the array of input conditions tags: function () {let tags = [] let keys = Object.keys (this.searchForm) keys.forEach ((key) = > {if (this.searchForm [key]) {tags.push (key)}) return tags}} Methods: {/ / Click to close close (tag) {this.searchForm [tag] =''this.$emit (' remove', tag)}, / / externally called method queryTable (searchForm) {this.searchForm = JSON.parse (JSON.stringify (searchForm))}, / / display name, if it is drop-down data Then go to the drop-down data to match until the name appears displayName (key) {let value = this.searchForm [key] if (this.selectionOption [key]) {return getTitle (value, this.selectionOption [key])} else {return value}. QueryInfo {margin-bottom: 10px }
The results are as follows:
Add feature button area
This is currently added to the searchTable component in the way of slots
{this.$slots.rightButton} / / use add
Effect:
This is the end of this article on "how to encapsulate query components based on element-ui". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
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: 273
*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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.