current position:Home>Vue Chapter 3 scaffolding's most complete render function, props, mixin mixing, plug-ins, browser local storage, component customization events_ Binding, unbinding, global event bus, message subscription and publishing, nexttick, Vue transition and animat

Vue Chapter 3 scaffolding's most complete render function, props, mixin mixing, plug-ins, browser local storage, component customization events_ Binding, unbinding, global event bus, message subscription and publishing, nexttick, Vue transition and animat

2022-05-15 01:21:25Tianhai has been

The third chapter —— Start shorthand

Install scaffolding

npm i -g @vue/cli

vue Create scaffolding

vue create Project name

cd Project name

npm run sever

http://localhost:8080/

Vue: The core + Template parser ( analysis template)

One 、render function

Use modular reference methods to reference vue

vue In bag package.json Medium module control ES6 Which specific js file

render Function has return value

Not used this You can use the arrow function

1、vue.js Full version

The core + Template parser ( analysis template)

2、vue.runtime.xxx.js No template parser , Need to use render Function received createElement Function to receive the specified content

new Vue({
    
	render:h => h(App)
})

Two 、 Modify the configuration file

Output scaffold profile command :vue inspect > output.js

establish vue.config.js Custom configuration

common expose :

module.exports = {
    
	pages:{
    
		index:{
    
			entry:'src/main.js'
		}
	},
	lintOnSave:false // Turn off grammar checking 
}

3、 ... and 、props

stay App.vue Write tag properties

<Student name=" Li Si " :age="18"/>   utilize v-bind

In components

export default {
    
	//props:['name','sex'] // Simple reception 
    /* At the same time, the data type is limited  props:{ name:String, age:Number } }*/
    // While receiving, the type of data is limited + The default value specifies + Necessity limits 
    props:{
    
        name:{
    
            type:String,
            required:true
        },
        age:{
    
            type:Number,
            default:0
        }
    }
}

Four 、mixin Mix in

mixins.js

function : The configuration shared by multiple components can be extracted into a mixed object

// Defining mixing 
{
    
	data(){
    
...
},
methods:{
    
...
}
}
        // Use mix in 
         The whole thing is in :Vue.mixin(xxx)
         To mix in partially :mixins:['xxx']

5、 ... and 、 plug-in unit

plugins.js

stay main.js Using plug-ins in

// Introducing plug-ins 
import plugins from './plugins'
// The use of plug-in 
Vue.use(plugins)

For enhancement Vue

contain install Method ,install The first parameter of Vue, The second parameter after is the data passed by the plug-in user

Define plug-ins :

 object .install = function(Vue,options) {
...
}

scoped style

Let the style take effect locally , To prevent conflict

<style scoped>

6、 ... and 、 Browser local storage

The local store localStorage:

Store... In the session sessionStorage Replace all with localStorage

Session storage sessionStorage:

<body>
    <h2>localStorage</h2>
    <button οnclick="saveData()">
         Click I save 
    </button>
    <button οnclick="readData()">
         Click I read 
    </button>
    <button οnclick="deleteData()">
         Click I delete 
    </button>
    <button οnclick="deleteAllData()">
         Click on me to empty 
    </button>
    
    <script type="text/javascript">
    let p = {name:' Zhang San ',age:18}
    function saveData(){
        sessionStorage.setItem('msg','hello')
        sessionStorage.setItem('msg2',666)
        sessionStorage.setItem('person',JSON.stringify(p))
    }
    function saveData(){
        console.log(sessionStorage.getItem('msg'))
        console.log(sessionStorage.getItem('msg2'))
        const result = sessionStorage.getItem('person')
        console.log(JSON.parse(result))
    }
    function deleteData(){
        sessionStorage.removeItem('msg2')
    }
    function deleteAllData(){
        sessionStorage.clear
    }
    </script>
</body> 

7、 ... and 、 Component custom events _ binding

stay APP.vue in

 Pass the function type from the parent component to the child component props Realization 
<School :getSchoolName="getStudentName" />
 Bind a custom event to the child component through the parent component to realize :  Sub payment transfer data ( Use @ or v-on)
<Student @yourname.once="getStudentName" />
 Bind a custom event to the child component through the parent component to realize :  Sub payment transfer data ( Use ref)
<Student ref="student"/>

ref The writing method uses mounted hook 
<script>
    export default{
        name:"App",
        components:{School,Student},
        data(){...},
    methonds:{
        getSchoolName(name){
            console.log('App Received the name of the school :',name)
        },
        getStudentName(name,...params){
            console.log('App Received student name ')
        }
    },
        mounted(){
        this.$refs.student.$on('yourname',this.getStudentName)// Binding custom events 
        this.$refs.student.$once('yourname',this.getStudentName)// Binding custom events ( Disposable )
        
    }
    }
	
</script>

8、 ... and 、 In components Student.vue Untie in

<button @click="sendStudentName">
     Give the students their names App
</button>
<script>
export default{
    name:'Student',
    data({
        ...
    })
},
     methods:{
         sendStudentName(){
             // Trigger Student Component instance yourname event 
             this.$emit('yourname',this.name,666,888,999)
             this.$emit('yourname')
         },
         unbind(){
             this.$off('yourname')// Unbind a custom event 
             this.$off(['yourname','yourname'])// Unbind multiple custom events 
             this.$off()// Unbind all custom events 
         }
     } 
</script>

Nine 、 Custom event summary of component :

Applicable to sub components ===> Parent component

Write the native tag attribute after the component and add .native

<Student @click.native="dianwo()">
     Am I 
</Student>

Trigger custom event :this.$emit('atguigu', data )

Be careful : adopt this.$refs.xxx.$on('yourname', Callback ) Binding custom events , Callback Or configure it in methods in , Or use the arrow function , otherwise this Point to the component instead of vm

Ten 、 Global event bus (GlobalEventBus): Communication between any components

1、 Install the global event bus

new Vue({
    
	.....
	beforeCreate(){
    
		Vue.prototype.$bus = this // Install the global event bus ,$bus Is the current application vm
	},
    .....
})

2、 Using the event bus

receive data :A The component wants to receive data , Then A In the component $bus Binding custom events , The callback of the event remains A The component itself

methods(){
    
	demo(data){
    .....}
}
...
mounted(){
    
    this.$bus.$on('xxx',this.demo)
},
beforeDestroy(){
    
    this.$bus.$off('xxx')
}

Provide data :this.$bus.$emit('xxxx', data )

3、 Best in beforeDestroy In the hook , use $off Unbind the events used by the current component .

11、 ... and 、 News subscription and Publishing (pubsub)

Import library npm i pubsub.js

receive data :

<script>
    // introduce 
	import pubsub from 'pubsub-js'
    export default {
        name:'School',
        data(){
            return{
                ....
            }
        },
        mounted(){
            this.pubId = pubsub.subscribe('xxx',(msgName,data)=>{
                console.log(' Someone has released xxx news ,xxx The callback of the message executes ',msgName,data)
            })
        },
        beforeDestroy(){
            pubsub.unsubscribe(this.pubId)
        }
    }
</script>

Provide data :

pubsub.publish('xxx', data )

Then it's best to beforeDestroy Unsubscribe from the hook

Twelve 、nextTick

grammar :this.$nextTick( Callback function )

effect : The next time DOM The callback specified by the executor after the update

When the data is changed , Based on the updated new DOM When doing something , To be in nextTick Execute... In the specified callback function

13、 ... and 、Vue Transition and animation

1、 Use

Element entry style :

v-enter: The starting point of entry

v-enter-active: In the process

v-enter-to: Enter the end of

2. The style that the element leaves :

v-leave: The starting point of departure

v-leave-active: In the process of leaving

v-leave-to: The end of leaving

2、 Use transition Wrap the elements to be excessive and configure name attribute

3、 Overuse of multiple elements <transition-group>, And specify key value

 <transition-group name="hello" appear>
            <h1 v-show="isShow" key="1"> How do you do </h1>
            <h1 v-show="isShow" key="2"> You too </h1>
</transition-group>

Use animate.css

Official website :animate.style

<template>
    <div>
        <button @click="isShow = !isShow"> Show / hide </button>
        <transition-group 
             name="animate__animated animate__bounce"  
             appear 
             enter-active-class="animate__swing"
             leave-active-class="animate__backOutUp">
            <h1 v-show="isShow" key="1"> How do you do </h1>
            <h1 v-show="isShow" key="2"> You too </h1>
        </transition-group>
    </div>
</template>
<script>
import 'animate.css'
export default{
    name:'Test',
    data() {
        return {
            isShow:true
        }
    },
}
</script>
<style scoped>
    h1{
        background-color:skyblue ;
        transition: 0.5s linear;
    }
 
</style>

fourteen 、 Configure agent

Method 1 :

stay vue.config.js Add the following configuration :

devServer:{
    
	proxy:"http://localhost:5000"
}

1、 advantage : Simple configuration , The requested resources can be sent directly to the front end

2、 shortcoming : Cannot configure multiple agents , Can't flexibly control whether the request goes through the agent

3. Operation mode : If the agent is configured as described above ( Priority matching front-end resources )

Method 2 :

module.exports = {
    
    devServer:{
    
        proxy:{
    
            '/api1':{
    // Match all to '/api1' The request path at the beginning 
                target:'http://localhost:5000',
                changeOrigin:true,
                pathRewrite:{
    '^/api1s:':''}
            },
            '/api2':{
    // Match all to '/api1' The request path at the beginning 
                target:'http://localhost:5001',
                changeOrigin:true,
                pathRewrite:{
    '^/api2:':''}
            },
        }
    }
}

1、 advantage : Multiple agents can be configured , And it can flexibly control whether the request goes through the agent

2、 shortcoming : Slightly cumbersome

15、 ... and 、vue-resource

npm i vue-resource

import vueResource from 'vue-resource'
Vue.use(vueResource)

copyright notice
author[Tianhai has been],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/132/202205120542422101.html

Random recommended