react,vue,angular

路由

vue路由

query

this.$router.push({
	path:'/select',
    query:{
    	id:this.id ,
    }
})
读取参数使用:this.$route.query.id
query参数会显示在地址栏

params

<router-link :to="{name:'Reg',params:{num:888}}">显示注册页面</router-link>
this.$router.push({
    name:'/select',
    params:{
    	id:this.id
    }
})
获取参数:this.$route.params.num
params传递参数在地址栏是看不到的

name和query也可以组合实现页面跳转,但是参数无法正常传递接收

react路由

params

<Route path='/path/:name' component={Path}/>
<link to="/path/2">xxx</Link>
this.props.history.push({pathname:"/path/" + name});
读取参数用:this.props.match.params.name

query

<Route path='/query' component={Query}/>
<Link to={{ path : ' /query' , query : { name : 'sunny' }}}>
this.props.history.push({pathname:"/query",query: { name : 'sunny' }});
读取参数用:this.props.location.query.name

state

<Route path='/sort ' component={Sort}/>
<Link to={{ path : ' /sort ' , state : { name : 'sunny' }}}> 
this.props.history.push({pathname:"/sort ",state : { name : 'sunny' }});
读取参数用:this.props.location.query.state 

search

<Route path='/web/departManange ' component={DepartManange}/>
<link to="web/departManange?tenantId=12121212">xxx</Link>
this.props.history.push({pathname:"/web/departManange?tenantId" + row.tenantId});
读取参数用:this.props.location.search

angular路由

queryParams

传递参数

<a [routerLink]="['/book']" [queryParams]="{id:key}">
this.router.navigate(['/book/'],{queryParams:{id:key}})

接收参数

import {ActivatedRoute} from '@angular/router'
constructor(public route:ActivatedRoute) { }
this.route.queryParams.subscribe((res)=>{
  console.log(res)
})

params

传递参数

<a [routerLink]="['/book',{id:key}]">
this.router.navigate(['/book/',{id:key}])

接收参数

import { Router} from '@angular/router'
constructor(public router:Router) { }
this.route.params.subscribe((res)=>{
  console.log(res)
})

生命周期

vue生命周期

beforeCreate

created        能获取到data

beforeMount

mounted        能获取到dom

(

     beforeUpdate          类似属性监听,会监听data的变化,data变化时触发钩子函数

     updated               以最小的demo开支重新渲染dom

)

beforeDestroy              组件销毁之前,仍然能访问到实例,可以做清除事件监听,定时器等

destroyed                  组件销毁后调用
props => methods =>data => computed => watch

react生命周期

constructor                        React数据的初始化,必须写super(props),否则会导致this指向错误

componentWillMount                 能获取到data,但获取不到dom,React 17已移除

componentDidMount                  能获取到dom

componentWillUnmount               组件的卸载和数据的销毁,removeEventListener,定时器

componentWillReceiveProps (nextProps)
    接收父组件传的props,在子组件内,props发生改变时触发,将nextProps的state为当前组件的state,React 17已移除,请使用static getDerivedStateFromProps(nextProps, prevState){}代替。
    
shouldComponentUpdate(nextProps,nextState)    通过返回的布尔值来控制是否重新渲染组件

componentWillUpdate (nextProps,nextState)
       shouldComponentUpdate返回true以后,组件进入重新渲染的流程,nextProps和nextState。React 17    已移除。
       
componentDidUpdate(prevProps,prevState)
     组件更新完毕后,react只会在第一次初始化成功会进入componentDidmount,之后每次重新渲染后都会进入     这个生命周期,这里可以拿到prevProps和prevState,即更新前的props和state。首次渲染不会执行此方法。
     

angular生命周期

constructor            除了使用简单的值对局部变量进行初始化之外,什么都不应该做
ngOnChanges            父子组件传值的时候会触发,首次调用一定会发生在ngOnInit()之前
ngOnInit               请求数据一般放在这个里面,只调用一次
ngDoCheck              自定义变更检测逻辑,手动去更改值,可以捕捉到data属性值的变化
ngAfterContentInit     当把内容投影进组件之后调用,ngDoCheck之后调用,只调用一次
ngAfterContentChecked  组件每次检查内容时调用,ngAfterContentInit和每次 ngDoCheck之后调用
ngAfterViewInit        组件相应的视图初始化之后调用,ngAfterContentChecked之后调用,只调用一次
ngAfterViewChecked     组件每次检查视图调用,ngAfterViewInit和每次ngAfterContentChecked之后调用
ngOnDestroy            销毁指令/组件之前调用并清扫,在 Angular 销毁指令或组件之前立即调用

ngAfterContentInit和ngAfterContentChecked

app.component.html

<app-aftercontent>
  <div style="color:red;" class="red">我是要投影的内容1</div>
  <p>我是要投影的内容2</p>
  <div style="color:yellow;" name="yellow">我是要投影的内容3</div>
</app-aftercontent>

ChildView.component.html

<p>
  <ng-content select=".red"></ng-content>
  <ng-content select="p"></ng-content>
  <ng-content select="[name=yellow]"></ng-content>
</p>
app.component.html中类名为red和p便签,以及name=yellow的元素会被显示

app.component.ts

ngAfterContentInit():void{
	console.log('父组件投影内容初始化完毕');
}

ngAfterContentChecked():void{
	console.log('父组件投影内容变更检测完毕');
}

ChildView.component.ts

ngAfterContentInit():void{
	console.log('子组件投影内容初始化完毕');
}
doing(){}
ngAfterContentChecked():void{
	console.log('子组件投影内容变更检测完毕');
}

ngAfterViewInit和ngAfterViewChecked

导入子组件,ngAfterViewInit,ngAfterViewChecked里能访问到子组件的属性和方法。但不能修改,修改必报错,但值得注意的是,手动修改后的值是能渲染到子视图上的。
@ViewChild(ChildViewComponent) viewChild: ChildViewComponent;
ngAfterViewInit() : void {
    console.log(this.viewChild.data)
}
ngAfterViewChecked() {
    console.log(this.viewChild.data)
}

获取dom元素

vue获取dom元素

<div ref="demo"></div>
this.$refs.demo
this.$refs.demo.style.color = 'red'

react获取dom元素

<div ref="demo"></div>
import  ReactDOM from  'react-dom'
ReactDOM.findDOMNode(this.refs.demo)
demo.style.color = 'red'

angular获取dom元素

<button #demo>goCount</button>
import {ElementRef,ViewChild,Renderer2} from '@angular/core';
constructor( private element: ElementRef, private renderer: Renderer2 ) {}
this.renderer.setStyle(this.demo.nativeElement,'color','red');
this.demo.nativeElement

获取事件源对象

vue获取事件源对象

<div @click="demo($event)">demo</div>
demo(e){
	console.log(e)
}

react获取事件源对象

<button onClick={this.demo}>demo</button>
demo(e){
    console.log(e.nativeEvent)
}

angular获取事件源对象

<button (click)="demo($event)">demo</button>
demo(e){
    console.log(e)
}

指令

vue指令

v-text		不会解析html标签
v-html		会解析html内容
v-show      display,初次渲染dom会执行,渲染后会缓存,css范畴,切换显示和隐藏频率高 就用v-show
v-if	    增删dom,js范畴,v-for 的优先级比 v-if 更高
v-for		<div v-for="(item, index) in items"></div>
v-model     <input v-model="test">

angular指令

 *ngFor			<li *ngFor="let hero of heroes">{{ hero }}</li>
 *ngIf			<p *ngIf="boolean">boolean</p>
 [src]			<img [src]="imgUrl">
 bind-src		<img  bind-src="imgUrl">
 [(ngModel)]	<input [(ngModel)]="name">
 [innerHTML]	<span [innerHTML]="html"></span>
 [ngClass]		<div [ngClass]="class"></div>
 [NgStyle]		<div [NgStyle]="style"></div>

组件传值

父传子

vue

父组件

<son :msg = 'message' ></son>

子组件

props:{
    msg:{
    	type: String,
    	default: ''
    }
}
props:['msg']

react

父组件

<Son data={this.state.data} />

子组件

this.props.data

angular

父组件

<Son [data]="data"></Son>

子组件

import { Input } from '@angular/core';
 @Input() data:number;

子传父

vue

父组件

<Son @func="getSonData"></Son>
methods:{
	getSonData(data){}
}

子组件

<button @click="sendData">父传子</button>
methods:{
    sendData(){
        this.$emit('func',this.msg)
    }
}

react

父组件

<Son  parent={ this } />
getChildrenMsg(result, data){
    result指向子组件的实例
}

子组件

<button onClick={ this.send }>父传子</button>
send(){
    this.props.parent.getChildrenMsg(this, this.state.data)
}

angular

父组件

<Son [sendChildData]="getChildData"></Son>
getChildData(childData) {
  alert(childData)
}

子组件

<button (click)="sendParent()">父传子</button>
@Input() sendChildData;
sendParent () {
    this.sendChildData(686)
}

状态管理

vue

main.js

import store from "store";

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

store.js

import main from 'main';
export default {
    state: {
      相当于data里的数据
    },
    getters:{
      相当于computed里的计算方法
    },
    mutations: {
      相当于methods里不包含异步处理的方法
    },
    actions: {
      actions提交的是mutations方法,这里可以包含异步处理操作
    },
    modules: {
      main
    }
}

main.js

export default {
	namespaced:true,			开启命名空间
	state: {
     	
    },
    getters:{
        
    },
    mutations: {
       
    },
    actions: {
        
    }
}
vuex和双向数据绑定的实现
<input v-model="modelData">
    
computed:{
	...mapState('main',['modelData'])		main为模块名
	modelData: {
      get () {
        return this.modelData;
      },
      set (value) {
        this.set_modelData(value);
      }
    }
}

methods: {
	...mapMutations('main',['set_modelData'])
}

mutations:{
    set_modelData(state,val){
    	state.searchData = val;
    }
}

react

安装两个依赖包redux,redux-thunk

App.js

import { store } from "store";
import  { Provider } from 'react-redux';
render(){
        return (
            <Provider store={store}>
                组件
            </Provider>
        );
    }

store.js

import {createStore,applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import reducer from 'reducer';
const middleware = [ thunk ];
export const store = createStore(reducer, {},applyMiddleware(...middleware))

reducer.js

import { combineReducers } from 'redux'
import item from 'item'
export default combineReducers({
    reducer:item
})

item.js

import { Add ,Post } from "Type";
const states = {
    pageTitle:686,
    infoList:68998
}
export  default function (state =states,action) {
    switch (action.type) {
        case Add:
            return {
                ...state,
                pageTitle:action.data
            }
        case Post:
            return {
                ...state,
                infoList:action.data
            }
        default:
            return state;
    }
}

Type.js

export const Add = "Add"
export const Post = "Post"

actions.js

import { Add ,Post } from "Type";
export  const add = (data) =>{
    return ( dispatch ) =>{
        console.log(data-1)
        dispatch({
            type:Add,
            data:data + 99
        })
    }
}
export  const post = (data) =>{
    return ( dispatch ) =>{
        console.log(data)
        dispatch({
            type:Post,
            data:data -100
        })
    }
}

Book.js

import React, {Component} from 'react';
import { add } from "action";
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

class Book extends Component {
    componentDidMount(){
        this.props.add(888);
    }
    render() {
        return (
            <div>
                { this.props.pageTitle }
            </div>
        );
    }
}

Book.propTypes = {
    pageTitle: PropTypes.number
};

const mapStateToProps = state => {
    return {
        pageTitle:state.reducer.pageTitle,
        infoList:state.reducer.infoList
    }
}
export default connect(mapStateToProps, { add })(Book);

angular

安装依赖包@ngrx/store

action.js

import { createAction,props } from '@ngrx/store';
export const increment = createAction('Increment',props<{ data: any }>());
export const decrement = createAction('Decrement');
export const reset = createAction('Reset');

reducer.js

import { createReducer, on } from '@ngrx/store';
import { increment, decrement, reset } from 'action';

export interface State {
  away: number;
  count: number;
}

export const initialState: State = {
  away: 0,
  count: 0
};

const _counterReducer = createReducer(initialState,
  on(increment, (state,data) =>{
    return {...state, count: state.count + data.data}
  }),
  on(decrement, state => ({...state, count: state.count - 1})),
  on(reset, state => ({...state, count: 0})),
);

export function counterReducer(state, action) {
  return _counterReducer(state, action);
}

select.js

import { State } from 'reducer';
import { createSelector } from '@ngrx/store';

export const countFeatureFn = (state: State, props) => {
  return state.away;
};

export const countStateFn = (state: State,props) => {
  return  state.count ;
};

export const countStateSelector = createSelector(countFeatureFn, countStateFn);

app.module.ts

import { counterReducer } from 'reducer';
import { StoreModule } from '@ngrx/store';
 imports: [
 	 StoreModule.forFeature('feature', counterReducer),
     StoreModule.forRoot({})
 ]

book.component.ts

import {State} from "reducer";
import {countStateSelector} from "select";
import {increment,decrement,reset} from "action";
import { Store, select } from '@ngrx/store';

count: Observable<number>;
constructor(private store: Store<{feature: State }>,private route:ActivatedRoute) {
    this.count = store.pipe(select(countStateSelector));
}
increment() {
    this.store.dispatch(increment({data:686}));
}

decrement() {
    this.store.dispatch(decrement());
}

reset() {
    this.store.dispatch(reset());
}

异步执行问题

同步任务
	new Promise((resolve,reject)=>{})
	resolve:允许后续执行then回调
	reject:允许后续阻止执行回调
	
	async函数在执行时是同步的,执行时能执行第一个await函数,每次执行完await函数,之后代码进入微观队列
        async function test(){
            await test1();
            await test2();
        }
	
异步任务分为
	微观任务:async/await,then,catch
	宏观任务:只有setTimeout,setInterval

任务执行顺序
	同步任务->微观任务->宏观任务
	微观任务执行看进入队列的顺序,先进先出
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值