one. Text out of range... Display
overflow:hidden;/*Hidden beyond*/ text-overflow:ellipsis;/*Excess display*/ white-space:nowrap;/*Force one line of text*/
two. Wrap text in excess
flex-wrap:wrap;/*Split line*/ white-space:normal;/*Forced text wrapping*/ word-wrap:break-word;/*The last word is not divided*/
/*Line feed*//**/ word-break:break-all;/* When the content reaches the width, it will wrap automatically. If the last word is long, it will be split and displayed */ word-wrap:break-word;/* When the content reaches the width, it will wrap automatically. If the last word is too long, it will not be divided and will go to the next line*/ text-align:justify/*Text horizontal alignment, two end alignment effect*/ text-justify:newspaper;/* Align text by increasing or decreasing spaces between letters to achieve end to end alignment */
three. Click on a light
<view class="left-item" v-for="(item,i) in leftList" :key="i" @click="activeLive(i)"> <view :class="['text', activeNum===i?'active':'']">{{item.cat_name}}</view> <view :style="{heighr:wh+'px'}"></view> </view> data() { return{ activeNum:0, wh:0 } }, methods: { activeLive(i) { this.activeNum = i } } &.active{ background-color: #eeee; }
4. Search box ceiling
/*Parent search box*/ position: sticky; top: 0; z-index: 999;
5. Click the tab, and the scroll bar on the right is not at the top
<scroll-view scroll-y class="right" :style="{height: wh + 'px'}" :scroll-top="scrollTop"> //Dynamic addition of right scroll bar: scroll top </scroll-view> //scrollTop: 0, //Left tab click event //activeLive(i) {this.scrollTop = this.scrollTop === 0 ? 0.5 : 0}
6. The input box has too many anti shake writes at one time
//timer:null, keywords: '' defined in data, //methods: input(e) { clearTimeout(this.timer) this.timer = setTimeout(()=>{ this.keywords = e },500) } //Anti shake let timer = null function debounce(fn,delay) { clearTimeout(timer) timer = setTimeout(()=>{ console.log('Anti shake') },500) } //throttle let valid = true if(!valid) return valid = false setTimeout(()=>{ console.log('Function throttling') valid = true },500)
7. Commodity list idea
·Product list page 1.Sending a request to obtain data requires parameter transfer 2.Parameter pass onload(value)Get parameters 3.adopt async await Get the data, and then render the data 4.Pull up load data judge pagenum the number of pages*pagesize Page size>total,Greater than return,No longer execute 5-judge isload True or false indicates that the data is still being requested, and the data is not available directly return,Do not execute the following pages++etc. First in page.js Medium style set up"onReachBottomDistance": 100 Number of pages pagenum++ Finally, re initiate the data request Rewrite the request method so that the data this.goodsList = [...this.goodsList,...res.message.goods] 5.Throttling prevents continuous drop-down. When the data is still requesting, the user will continue to pull-down data() Defined in isload: false methods In, the value is assigned to before the request is sent true this.isload = true,After the data request is sent, the assignment is false this.isloading = true const {data:res} = await this.$myRequest({ url: '/api/public/v1/goods/search', data: this.goodsListParams, }) this.isloading = false 6 Drop down refresh data stay page.js Middle opening "enablePullDownRefresh": true, Call method onPullDownRefresh(),Reassign some important data Number of pages, total amount, data list isload,A function that re initiates the request and passes in a stopped refresh this.getGoodsList(() => {uni.stopPullDownRefresh()}),Then rewrite the parameters passed in by the request method getGoodsList(cb) {cb&&cb()}//This method is very appropriate. You don't need to write setTimeout to set the time to turn off the refresh icon <template> <view> <view class="goodlist-box"> <view class="goodlist-item" v-for="(item,i) in goodsList" :key="i" @click="gotoGoodDetail(item)"> <my-goodlist :goodsList="item"></my-goodlist> </view> </view> </view> </template> <script> export default { data() { return { isloading: false, goodsListParams:{ query: '', cid: '', pagenum: 1, pagesize: 10 }, goodsList:[], total:0, defaultpg:'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1212681992,4124630859&fm=26&gp=0.jpg' }; }, onLoad(value) { console.log(value) this.goodsListParams.cid = value.cid || '' this.goodsListParams.query = value.query || '' this.getGoodsList() }, methods: { async getGoodsList(cb) { this.isloading = true const {data:res} = await this.$myRequest({ url: '/api/public/v1/goods/search', data: this.goodsListParams, }) this.isloading = false cb&&cb() this.goodsList = [...this.goodsList,...res.message.goods] this.total = res.message.total }, gotoGoodDetail(item) { uni.navigateTo({ url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id }) } }, // Pull up loading onReachBottom() { if(this.goodsListParams.pagenum * this.goodsListParams.pagesize > this.total) { return uni.showToast({ title:'What the hell am I' }) } //If isloading is true, the following code will not be executed when requesting data if(this.isloading) return this.goodsListParams.pagenum++ this.getGoodsList() }, // Pull down refresh onPullDownRefresh() { this.goodsListParams.pagenum = 1 this.total = 0 this.isloading = false this.goodsList = [] this.getGoodsList(() => {uni.stopPullDownRefresh()}) } } </script>
8. Search Page Ideas
- Using the uni UI layout search box, when inputting content, the input method can obtain the input content - keyword, and perform the throttling function for user input to prevent users from inputting and outputting results quickly all the time
- Initiate a query request. The request parameter is to enter the content keyword, get the result searchList, write the ui framework for rendering, beautify after rendering, click the corresponding list to jump to the commodity list, and pass in the parameter item, uni Navigator ({URL: '}) to jump to the product list
- If there is no search term, you need to reset the searchlist to empty. return it before requesting data
- Save the keywords entered in the search box to the searchHistoryList. Use the set method so that the obtained values will not be repeated. Set gets the object, which needs to be through array From is converted into an array, and the searchHistoryList can be reversed through the computed calculation attribute, so that the most recent search is in the front. Finally, the searchHistoryList will be obtained through JSON Stringify saves to local Storage Uni setStorageSync('keyword', JSON.stringify(this.historylist))
- In onload, you need to get the locally saved searchhistorylist. This value may be empty, this searchHistoryList = JSON. Parse (uni. Getstoragesync ('keyword ') |' '), you need to convert the key: value saved in string form in local Storage to JSON object format
<template> <view> <view class="search"> <uni-search-bar :cancelButton="none" :radius="100" @input="input" ></uni-search-bar> </view> <view class="response" v-if="queryList.length!==0"> <view class="search-text" v-for="(item,i) in queryList" :key="i" @click="gotoGoodsList(item)"> <text>{{item.goods_name}}</text> <uni-icons type="arrowright" size="18" ></uni-icons> </view> </view> <view class="history-box" v-else> <view class="history-delete"> <text>Search history</text> <uni-icons class="trash" type="trash" size="18" @click="deleteList"></uni-icons> </view> <view class="history-list"> <!-- <view class="" v-for="(item, i) in historys" :key="i"> <uni-tag :text="item" @click="gotoTag(item)"></uni-tag> </view> --> <uni-tag :text="item" @click="gotoTag(item)" v-for="(item, i) in historys" :key="i"></uni-tag> </view> </view> </view></template><script> export default { data() { return { timer: null, // key word keyword:'', // Search results list queryList:[], // History list historylist:[] }; }, // Get locally saved search records onLoad() { // Be sure to | '', otherwise the user who just came in will report an error if he has no record this.historylist = JSON.parse(uni.getStorageSync('keyword') || ''); }, computed:{ // Reverse the search record list, and the last search is at the front historys() { return [...this.historylist].reverse() } }, methods: { // Anti shake to prevent users from entering quickly input(e) { // console.log(e) clearTimeout(this.timer) this. timer = setTimeout(()=>{ this.keyword = e console.log(this.keyword) this.getQueryList() }, 500) }, // Delete history information deleteList() { this. historylist = [] uni.setStorageSync('keyword', '') }, // Jump to product list page gotoTag(item) { uni.navigateTo({ url:'/subpkg/goods_list/goods_list?query=' + item }) }, // Get recommended query async getQueryList() { // Determine whether the keyword is empty if(this.keyword == '') { return this.queryList = [] } const {data:res} = await this.$myRequest({ url: '/api/public/v1/goods/qsearch', method: 'GET', data:{query: this.keyword} }) console.log(res.message) this.queryList = res.message // After the data is obtained, the method of saving is performed this.saveSearchHistory() }, // Store data saveSearchHistory() { // this.historylist.unshift(this.keyword) // Using the set method, only a single value can be obtained and will not be repeated const res = new Set(this.historylist) res.delete(this.keyword) res.add(this.keyword) console.log('res:',res) console.log(typeof res) this.historylist = Array.from(res) // Save the keywords entered in the search box in the form of JSON string in Storage uni.setStorageSync('keyword', JSON.stringify(this.historylist)) }, // Jump to product details page gotoGoodsList(item) { uni.navigateTo({ url:'/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id }) }, } }</ script><style lang="scss">. search{ position: sticky; top: 0; z-index: 999; background-color: #C00000;}.search-text{ display: flex; justify-content: space-between; align-items: center; padding: 15px; text{ overflow:hidden;/* Hidden beyond*/ text-overflow:ellipsis;/* Excess display*/ white-space:nowrap;/* Force one line of text*/ font-size: 14px; color: #424242; }}. history-delete{ display: flex; justify-content: space-between; align-items: center; padding: 5px 10px; border-bottom: 1px solid #efefef; text{ font-size: 14px; }}. history-list{ padding: 5px; display: flex; flex-wrap: wrap; . uni-tag{ margin-right: 8px; margin-top: 8px; }}</ style>
9. Add product details to shopping cart logic
- Click the add shopping cart button to increase the number of shopping cart icons
- Import the shopping cart uni goods NAV through the uni UI plug-in, and then go through two click events, click and buttonclick
- Use vuex to manage shopping cart data in cart JS, write a judgment method addToCart(state, goods) and pass in two parameters (state, goods) to judge whether the clicked commodity is in the shopping cart. If not, push the commodity to the shopping cart to get the cart array. If it exists, let count++
- In the buttonclick event on the product details page, first judge that the click is the add shopping cart button with index==0, then call the judgment method addToCart(goods) of changes, and define the parameter object - goods. The parameter goods needs to define 6 data
- In cart JS defines the calculation attribute getters, defines the total function, and uses the forEach function to calculate the number of shopping carts
- On the product details page, the watch listener defined in the form of ordinary function will not be called after the page is loaded for the first time. The watch listener is defined in the form of object, immediate:true
// cart.js / / initialize cart JSexport default { // Open the namespace of the current module namespaced: true, // State data of the module state: () => ({ // An array of shopping carts, which is used to store the information object of each commodity in the shopping cart // The information object of each commodity contains 6 attributes: // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state } cart: JSON.parse(uni.getStorageSync('cart ') |' [] '/ / persist to local data Storage }), // Module's mutations method mutations: { addToCart(state, goods) { // According to the submitted commodity ID, query whether there are commodities in the shopping cart. If there are no commodities, add them to the shopping cart. If there are commodities, add one to the quantity // The find() method returns the array if it exists, and undefined if it does not exist const findResult = state. cart. find(x => x.goods_id === goods.goods_id) if(!findResult) { state.cart.push(goods) } else { findResult.goods_count++ } uni.setStorageSync('cart', JSON.stringify(state.cart)) // this.commit('m_cart/saveToStorage') }, // saveToStorage(state) { // uni.setStorageSync('cart', JSON.stringify(state.cart)) // } }, // Getters attribute of module getters: { // Calculate the number of shopping carts total(state) { let num = 0 state. cart. forEach(goods => num += goods.goods_count) return num } }, // Actions method of module actions: { }}// goods_ detail. jsbuttonClick(v) { // console.log(v) if(v.index == 0) { const goods = { goods_id: this.goodsDetailList.goods_id, goods_name: this.goodsDetailList.goods_name, goods_price: this.goodsDetailList.goods_price, goods_count: 1, goods_small_logo: this.goodsDetailList.goods_small_logo, goods_state: true } this. Addtocart (goods)}} Watch: {total: {handler (newval) {const findresult = this. Options. Find (x = > x.text = = 'shopping cart') if (findresult) {/ / 3. Dynamically assign findresult.info = newval}, immediate: true}} to the info attribute of the shopping cart button,
10. Shopping cart item radio icon check status
-
In cart In Vue, bind custom click events in my goodslist, @ radio change = "radiochange"
-
In the subcomponent my goodslist In Vue, bind the radio to the click event @ click=radioChangemd
-
In vuex's store / cart JS defines the method updataGoodsState for operating shopping cart state information
<view v-for="(goods,i) in cart" :key='i'> <my-goodlist :goodsList="goods" :showRadio="true" @radio-change="radioChange"> </my-goodlist></view>radioChange(e) { console.log(e)}// The parameters of the child component will be passed to the parent component, e becomes an object with two key values < radio V-IF = "showradio": checked = "goodslist. Goods_state" color = "#c00000" @ Click = "radiochange" / > radiochangemd() {this. $emit ('radio change ', {goods_id: this. Goods_id, goods_state:! This. Goods_state})} / / goods is just a formal parameter updatagoodsstate (state, goods) {const findresult = state.cart.find (x = > x.goods_id = = = goods. Goods_id) if (findresult) {findresult. Goods_state = goods. Goods_state} / / cache the updated information cart to the local Uni setStorageSync('cart', JSON.stringify(state.cart))}
11,JSON.stringify() ,JSON.parse()
json.stringify() converts JavaScript objects into strings, JSON Parse () converts a JavaScript string into an object
1.localStorage/sessionStorage can only store strings by default. In actual development, most of the data we store are object types, so we can: use JSON Stringify () converts the object into a string, and uses JSON. XML when fetching the cache Parse() can be turned back to the object
//uniapp setStorageSync('keyword', JSON.stringify(this.history))this. history = JSON. Parse (uni. Getstiragesync ('keyword ')) / / function setLocalStorage(key,val) in JS{ window.localStorage.setItem(key, JSON.stringify(val))}function getLocalStorage(key){ let val= JSON.parse(window.localStorage.getItem('keyword')) return val}setLocalStorage('keyword', [12,122])
2. Implement object deep copy
//Deep copy function deepclone (data) {let _data = JSON. Stringify (data) let dataclone = JSON. Parse (_data) return dataclone} / / test let arr = [1,2,3] let_ arr = deepClone(arr)arr[1] = 4console. log(arr, _arr)//[1,4,3] [1,2,3]
12,JSON.stringify(),toString()
Although both can turn the target into a string, the essence is different
let arr = [1,2,3]JSON.stringify(arr) // '[1,2,3]'arr.toString(arr) // 1,2,3
13. Array common
13.1. forEach() does not change the original array
forEach(): the method performs a callback operation on each element of the array. The callback can accept three parameters; The first value (required) - the element currently being processed in the array, the second index (optional) - the index of the element currently being processed in the array, and the third array (optional) - the array currently being processed. Thisarg (optional), used as the value of this when the callback function callback is executed.
Syntax: array forEach(callback(value,index,array), thisArg)
// Function sum (ARR) {var s = 0; arr.foreach (function (value, index, array) {/ / arr.foreach (value = > {S + = value}) ES6 syntax S + = value}) return s}
13.2. filter() does not change the original array
filter(): the method will create a new array, which contains all elements that pass the implementation test. If not, it will return an empty array. callback is a function used to test each element of the array. If it returns true, it will pass, and the new array will be retained. If false, it will not be retained in the new array. callback accepts three parameters: the first element - the element currently being processed in the array, the second index (optional) - the index of the element currently being processed, and the third array (optional) - the current array
Syntax: array. Filter (callback (element, index, array), thisarg)
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];const result = fruits.filter(x => x==='apple') // ['apple '] / / delete the last element function fliter(array){ return array. filter((val,index,arr) => { return index !== arr.length-1 // If the index of the current test is not equal to the last one, it will be true and added to the new array})}
13.3. find() does not change the original array
find(): the method returns the value of the first element in the array that meets the test function, otherwise it returns undefined. Description: test each element in the array, execute the callback function once until the result is true, and return the value of this element.
Syntax: array. Find (callback (element, index, array), thisarg)
var inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5}];function finds(inventory) { return inventory.find(vlaue => { return value.name === 'apples' })}// {name: 'apples', quantity: 2}
13.4 slice() does not change the original array
slice(): the method returns a new array that has been extracted. The original array will not be changed, and 2 parameters are accepted; The first start (optional), the start position contains, the second end (end), and the end position does not contain. The intercepted elements will be added to the new array, and those not intercepted will be discarded, which is equivalent to deletion.
Syntax: array slice(begin,end)
// Delete the last element in the array const array = ['demo', 'love', 'drive', 'Dance', 'foreach'] const array2 = array slice(0, -1) // Intercept the 0 th to the last, and the last does not include console log(array2) // ['demo', 'love', 'drive', 'dance'] function delete(arr) { return arr.slice(0, -1)}
13.5 change splice() to the original array
splice(): the method will delete or modify the array and change the original array. The first parameter: start counts from 0. If it is negative, it indicates the penultimate digit. The second parameter: deleteCount, the number of deleted items. If it is 0, it will not be deleted. The third parameter: item, it indicates the content to be added
Syntax: arr.splice(start,deleteCount,item)
const months = ['Jan', 'March', 'April', 'June'];months.splice(1, 0, "Feb");console.log(months);// ["Jan", "Feb", "March", "April", "June"]
13.6 change unshift() to the original array
unshift(): modifies the original array, adds one or more elements to the beginning of the array, and returns the new length of the array.
Syntax: arr.unshift(element)
// Add elements in front of the array without changing the original array const months = ['Jan', 'March', 'April', 'June']const new_array = months.slice(0)new_array.unshift('item')// ['item', 'Jan', 'March', 'April', 'June']
13.7. Change push() to original array
push(): the original array will be modified. The method adds one or more elements to the end of the array and returns the new length of the array.
Syntax: arr.push(element)
const months = ['Jan', 'March', 'April', 'June']months.push('item')// ['Jan', 'March', 'April', 'June', 'item']
13.8 concat() does not change the original array
concat(): the method is used to merge two or more arrays. The original array will not be changed, but a new array will be returned
Syntax: var new_array = old_array.concat(value_array)
// The merged array must be an array var array = ['a ',' B ',' C '] var array2 = ['d'] concat(array)// array 2: ['d', 'a', 'b', 'c']var array3 = array.concat(['d'])// array3: ['a', 'b', 'c', 'd']function concat(arrat,item) { return [item].concat(array)}
13.9,indexOf()
indexOf(): the method returns the first index of a given element that can be found in the array. If it does not exist, it returns - 1. Parameter 1: the element to be searched. Parameter 2: index value
Syntax: arr.indexOf(item,index)
var arr = ['a', 'b', 'c']arr.indexOf('a') // 0
13.91,reducer()
reducer(): the method executes a provided reduce function for each element in the array and summarizes the results into a single return value.
Accumulator: accumulator CurrentVlaue: current value CurrentIndex: current index Array: Array
InitialValue: the initial value of the accumulator. If not, the first element in the array will be used
Syntax: arr.reduce(callback(accumulator,currentValue,index,array), initialValue)
When the callback function is executed for the first time, the values of accumulator and currentValue are in two cases: if initialValue is provided when calling reduce(), the value of accumulator is initialValue, and currentValue takes the first value in the array; If initialValue is not provided, then the calculator takes the first value in the array and currentValue takes the second value in the array.
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { return accumulator + currentValue}, 10)// 20
13.92,flat()
flat(): the method will recursively traverse the array according to a specified depth, and merge all elements and the elements in the traversed sub array into a new array to return.
Syntax: var newArray = arr.flat([depth])
var arr1 = [1, 2, [3, 4]]arr.flat() // [1,2,3,4]var arr2 = [1, 2, [3, 4, [5, 6]]]arr2.flat() // [1, 2, 3, 4, [5, 6]]var arr3 = [1, 2, [3, 4, [5, 6]]]arr3.flat(2) // [1, 2, 3, 4, 5, 6] / / use infinity to expand the nested array arr4 at any depth flat(Infinity) // [1, 2, 3, 4, 5, 6]
13.93,some()
some(): the method tests whether at least one element in the array passes the test of the provided function, and the return value is a Boolean value. If at least one element in the array passes the test of the callback function, it will return * * true * *; All elements fail to pass the test of the callback function, and the return value will be false.
When callback is called, three parameters are passed in: the value of the element, the index of the element, and the traversed array.
Syntax: ar.some (callback (element, index, array), thisarg)
function isBiggerThan10(element, index, array) { return element > 10;}[2, 5, 8, 1, 4].some(isBiggerThan10); // false[12, 5, 8, 1, 4].some(isBiggerThan10); // true
13.94,from()
from(): method creates a new array instance from a similar array or iteratable object
arrayLike: a pseudo array object or iteratable object that you want to convert to an array
mapFn: the callback function is executed for each element in the new array
thisArg: this object when executing the callback function mapFn
Syntax: array from(arrayLike, mapFn,thisArg)
const set = new Set(['foo', 'bar', 'baz', 'foo'])Array.from(set) // ["foo", "bar", "baz"]
13.95,sort()
sort(): sort the elements of the array and return the array.
Syntax: arr.sort(first, second)
var numbers = [4, 2, 1, 3, 5]numbers.sort((a, b) => a-b)log(numbers) // [1,2,3,4,5]numberss.sort((a, b) => b-a)log(numberss) // [5,4,3,2,1]
-
map()
The map() method will return a new array. The elements in the array are the values processed by the calling function of the original array. The empty array will not be detected and the original array will not be changed
let array = [1,2,3,4,5]let newArray = array.map(item => { return item * item})console.log(newArray) // [1, 4, 9, 16, 25]
-
set()
The set object allows you to store unique values of any type. The values will not be repeated, and a set object will be returned
let mySet = new Set();mySet.add(1); // Set [ 1 ]mySet.add(5); // Set [ 1, 5 ]mySet.add("some text"); // Set [ 1, 5, "some text" ]const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]console.log([...new Set(numbers)])// [2, 3, 4, 5, 6, 7, 32]
-
find()
The find() method returns the value of the first element in the array that satisfies the provided test function. Otherwise, it returns undefined
var arr = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5}]const findResult = arr.find(y => y.name === 'apples')// Object {name: 'apples', quantity: 2}
-
filter()
The filter() method creates a new array and returns the elements that meet the provided function test. If none of them meet, it returns an empty array
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];const result = fruits.filter(x => x.name==='apple') // {name: 'apple'}
-
forEach()
The forEach() method performs a pointwise function on each element of the array
const array1 = ['a', 'b', 'c'];array1.forEach(element => console.log(element));// expected output: "a"// expected output: "b"// expected output: "c"
-
indexOf()
The indexOf() method can find the first index of a given element. If it exists, it returns the index. If it does not exist, it returns - 1
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];console.log(beasts.indexOf('bison'));// expected output: 1// start from index 2console.log(beasts.indexOf('bison', 2));// expected output: 4console.log(beasts.indexOf('giraffe'));// expected output: -1
-
join()
The join() method concatenates all elements of an array into a string and returns the string
const elements = ['Fire', 'Air', 'Water'];console.log(elements.join());// expected output: "Fire,Air,Water"console.log(elements.join(''));// expected output: "FireAirWater"
-
Difference between map and filter
var array = [{key: 1, value: 10}, {key: 2, value: 20}, {key:3, value: 30}]var mapRes = array.map((v,i) => {return v.value = v.value+'s'})console.log(mapRes) //['10s',' 20s', '30s'] / / map can return a new array, and the content format can be part of the original array. Var filterres = array filter((v,i) => {return v.value=v.value+'s'})console. Log (filterres) / / [{key: 1, value: '10ss'}, {key: 2, value:' 20ss'}, {key: 3, value: '30ss'}] / / the array returned by the filter is consistent with the original array structure
14. Use of vuex
-
First create a store in the root directory – > store JS initializes the instance object
// store/store.js--// 1. Import vue, vueximport Vue from 'vue'import Vuex from 'vuex'// 2 Set vuex as vue plug-in vue use(Vuex)// 3. Create an instance object storeconst store = new vuex Store ({state: {}, getters: {}, variations: {}, actions: {}, / / Mount store module modules: {}}) / / 4 Export instance object storeexport default store
-
In main JS and mount it on the vue instance
// main.jsimport Vue from 'vue'import App from './App'#import store from './store.js'import { myRequest } from 'util/index.js'Vue.config.productionTip = falseApp.myType = 'app'const app = new Vue({ ...App, #store})app.$mount()
-
Create a shopping cart store module, cart JS, initialize vuex module
// store/cart.jsexport defaule {/ / open the module namespace named: true, state: () = > ({}), variations: {}, getters: {}, actions: {}
-
In the store JS module, import and mount the vuex module of the shopping cart
// store/store.jsimport Vue from 'vue'import Vuex from 'vuex'import moduleCart from './cart.js'Vue.use(Vuex)const store = new Vuex.Store({/ / mount the store module modules: {/ / mount the vuex module of the shopping cart. The access path of members in the module is adjusted to m_cart m_cart: modulecart}}) export default store
-
Yes vue page usage
// goods_detail.vue You don't need to use this < view class ='yf '{{cart. Length} < / View > / / you need to specify the name of the module whether you map the changes method, the getters attribute, or the data in state, Can be mapped import {mapstate} from 'vuex' export default {computed: {/ /... Mapstate ('name of module ',' name of data to be mapped 1 ',' name of data to be mapped 2 ')... Mapstate ('m_cart', ['cart '])}}
15,JQuery
15.1. Multi box selection method
<input class="getFocus_userid" name="circle" type="checkbox" id="{$vo.focus_userid}" /><span>{$vo.realname}</span><!-- id The value of is a number--><script> $("#btn").click(function() { var ids = '' $('.confirm').each(function() { if($(this).is(":checked")) { // if(this.checked == true) { if(ids == '') { ids = $(this).attr('value') } else { ids = ids + ',' + $(this).attr('value') } } }) console.log(ids) })</script>
// indexOf + push to add whether checkboxarr = [] gotofocus = function (item) {Item2 = json.parse (item). id var useid = arr.indexof (Item2) / / judge the input click event, click trigger, define an empty array, click for the first time, judge whether id exists in the array, add if it does not exist, delete if it exists (useid = = - 1) {arr.push (Item2)} else { arr.splice(useid,1) }}
16,BFC
<!-- One BFC Contains all child elements that create the context element, but does not contain child elements. A new context element is created BFC Internal elements of One element cannot have 2 BFC in BFC The most important role is: in BFC Internal elements are isolated from external elements BFC:The block level formatting context is a separate rendering area Element generation BFC Conditions met: 1: Root element 2: float Value is not none 3: overflow Value is not visible 4: display Value is inline-block,table-cell,table-caption 5: position Value is absolute perhaps fixed BFC characteristic: 1: The inner boxes are arranged vertically 2: In the same BFC Under the element, may occur margin overlap 3: Of each element margin box Left and container block border box The left side of the will touch 4: BFC An isolated, independent container of child elements within, isolated from the outside --> <!-- trigger BFC: Root element float Not for none,overflow Not for visible,display by inline-block,position Value is absolute perhaps fixed -->
17. Add cart rendering logo
1,For shopping cart data vuex To manage data and create store.js Enable modules:{},It can manage multiple modules, which only need to be filled in name,Write the status of managed data in each branch module: namespaced,state,getters,mutations,actions. 2,Trigger add shopping cart event: in branch cart.js in mutations Write the addition method and introduce it to the product details page. To use this method, you need to transfer parameters. 3. Add cart data rendering: in cart.js in getters Pair cart The calculation of data is used to accumulate the number of goods in the shopping cart and use it in the details page watch For the change of listening data, the listener will not be triggered because it is just loaded, so it needs to be modified and used handler+immediate,take handler(e)Accepted changes e Assign to shopping cart options of info. 4,Save data localized: in branch cart.js in mutations Define the method. 5. In tabBar Render digital logo on 4 tabBar Page introduction vuex of total Count, and render the page with this total number, uni.setTabBarBadge({index:2, text: 'character string'}),You need to render the page as soon as it comes in onShow()Call save: uni.setStorageSync('cart',JSON.stringify(state.cart))Take: JSON.parse(uni.getStorageSync('cart') || '[]') There is a possibility that it is empty mutations One method in calls another method: this.commit('cart/saveStorage')
1,What are the advantages of your blog system? Because the system is aimed at individual users, users can use it very conveniently, which is convenient for others to preview their blog content. The page layout is beautiful and easy to operate. Users without computer foundation can also use it. 2. What is the design idea of your verification code? Front end initiated by get Request to obtain the four random numbers obtained by the interface, and then jquery Plug in validate Shoulder pole verification is for you to verify whether the input characters are consistent with the obtained verification code. 3. What else do you think can be improved? It can optimize the information shielding function of the content and mask some sensitive information with keywords, so as not to cause adverse effects. Add a follow blog user function to follow the favorite bloggers and find the ones that can be changed next time
18,router
18.1 transmission of reference
-
Pass parameters through URL
For example:? Name = index & key = value obtaining method: this$ route. query
-
Placeholder for passing routing rules
For example, / name/value can be obtained by this $route params
18.2 human legacy
const routes = [ {path: '/', redirect: '/login'}, {path: '/login', name: 'login', component: Login}, {path: '/home', name: 'home', component: ()=>import('@/views/video')},// Lazy load {path: '/ my', name: 'my', children: [{path: '', name: 'QA', component: () = > Import ('@ / views / QA')}, / / there can only be one default sub route {path:'/video', name: 'video', component:()=>import('@/views/video')} ]}]